Active4 years, 7 months ago

I am a beginner in java and I have written this code with the help of an online available program. The code attached is a part of the code which performs action when buttons of the calculator are pressed.In the CalculatorDemo class i have initialized all the buttons(b0-b24) and the TextField tf. In this class I am using char OP as a flag ,so that, when I press '+' the OP is assigned '+' and I have even checked it on command prompt. But when i press '=' ,the OP is automatically assigned '0' and i don't know how and why. And hence, no operation is performed at all. And I don't understand where the logic is wrong. Please help


Simple calculator in Java. Import java.util.Scanner; public class Calculator. Program to check if a date is valid or not. Algorithm Of A Simple Age Calculator In Java Codes and Scripts Downloads. Job Sequencing With Deadline C Program: Website Value. Model of a simple trebuchet that predicts projectile range based on fulcrum position.

Trebuchet Calculator Program Java

4 Answers

I'm not going to go into the code you have posted in your questions, but rather attempt to help you attack your overall goal of writing a calculator demo.

The first step should be to get a clear idea of the problem by writing it down:

I need a calculator with a display and a keypad with the digits 0-9 and the operators +,-,x,/ and an = button. The calculator should read a series digits from the keypad, then a mathematical operator, then another series of digits and so on. Each uninterrupted series of digits should be converted into an integer value.

The calculator should calculate the result of applying the mathematical operator to the first and second integer values. If further operators and integers are entered, the mathematical operator should be applied to the result of the prior calculation and the further integer. This process should continue until the equals button is pressed. When digits are pressed on the keypad they should appear in the text display appended to those digits entered so far.

When an operator or the equals button is pressed this signals the end of the entry of an integer, if this completes a calculation then the result should be shown on the display, otherwise the integer should remain in the display until another digit is pressed - then the display should be cleared and the new digit displayed, and subsequent digits appended, as before.

From this description we can identify some nouns: Calculator, Button, Display, Keypad, Digit, Operator, Integer, Result..and some verbs: Read, Press, Convert, Calculate, Apply, Enter, Complete, Show, Remain, Clear, Display, Append

These give us an idea of the state and behaviour required for our program. We then decide how to model these in our implementation. Typically nouns can be modelled as classes/instance variables (state) and verbs as methods (behaviour).

Here is one possible design:

A class called Calculator using Swing components to represent the Buttons/Keypad and Display; using the primitive int type for representing Integer/Result/Digit; using Java mathematical operators for representing Operator.

Let's start to make the bones of this:

Trebuchet Size Calculator

Now we need to work out how we are going to Read/Press buttons. We will need to set up our JButtons to respond to being activated and wire up that event to a method we define in our Calculator class.

One way to do this is to create the JButtons and add a listener to them. We can make Calculator implement the ActionListener interface, which forces it to define a method actionPerformed with a single ActionEvent argument. We can see how this would work by creating a JButton in Calculator's constructor.

Note this code won't do anything yet because we haven't set up the window and connected the button to it. However, the code should illustrate how we can run code from a button press.

Let's get on and get this code in a working state by setting everything up:

OK, we need more than one button, we need a whole load. Let's make digits 0-9:

Trebuchet Calculator Program Javascript

Hmm that didn't work right - only one button appears on the window. That's because we have the default window layout which isn't what we need. We want the buttons to appear in a grid, grouped together in the window. Let's create a JPanel to group the buttons together in and use a GridLayout for the panel, then we can add the panel to the window.

That's not bad, but the numbers don't come up in the usual order you'd see on a numpad. That's because they appear in the order added from top-left to bottom-right. We can fix that by specifying the order we want with an array, and iterate through that (we use the for-each style iterator for this because it's neater). While we're doing that, we can do something similar for the mathematical operators and equals button and add them to the frame too (here we'll be explicit about the layout to use for the window and we'll use a BorderLayout).

OK, we're nearly done with the components. We just need to add a display.

Now we just need to implement the logic to respond to button presses. First, let's see what we need to do if a digit is pressed. We need to deal with the Append and Show verbs and append that digit to our input and display it.

Cool. Now we need to implement the Convert verb and convert our digits into an integer. This will happen when an operator or equals is pressed. We need to remember what operator was pressed so we know what calculation to do when the second integer is entered.

Now we actually need to handle the second time an operator or equals is pressed, when we already have an integer and operator saved away. Here we can implement the + part of the Calculate/Apply verb and Show the result.

This isn't quite right. It will put into result the sum of the previous 2 integers rather than the sum of all integers entered so far. We need to store the first value in result then add each subsequent integer to the value stored in result. This means we don't need the previousInteger variable any more, and we have some duplicate code in both the if and else that we can just execute before the if.

Let's implement the other operators.

Here we make = an operator that acts like a reset and allow us to start a new calculation. You may notice you get an error if you try to hit = then + (to add a number to the result); this is because there are no digits in the input to convert to an integer for the + operator. We can solve this by skipping the calculation in this case.

Here is the full code so far. It doesn't handle divide by 0, keypad is never used and can be removed, and integerEntered really need only be a local variable and not a instance variable. However, the code should mostly work, let me know if you spot any problems. I also have a cleaner version (the first implementation I did) but it wasn't so simple to explain.

Here's the cleaner, but more complicated version:

Mike TunnicliffeMike Tunnicliffe

Calculator Program Code

9,3383 gold badges24 silver badges46 bronze badges
Bhumi PatelBhumi Patel
Bhumi PatelBhumi Patel
4,48512 gold badges23 silver badges30 bronze badges

Not the answer you're looking for? Browse other questions tagged java or ask your own question.