# Calculator

• June 26th, 2012, 03:15 AM
ikocijan
Calculator
Hello,
can someone help me with this code (it is a calculator with ActionListener):

Code :

```else if (src == referenca.buttonPlus)//when someone press button + {   num=referenca.getDisplay();//gets the number that someone typed and saves it into variable num   numStringToDouble = Double.parseDouble(num);//Converts String to Double   matOperacija="+"; //saves mathematical operations - I have set this variable to be INT but I am not sure what should it be INT,CHAR,STRING...   referenca.setDisplay ("",""); //sets blank display   }   //here should be buttonMinus, buttonMultpy etc...all the same as buttonPlus   else if (src == referenca.buttonEqual) { String equal= referenca.getDisplay(); //gets displayed number   Double newEqual =Double.parseDouble(equal); //converts displayed number into double   Double result = //here is where I should use a mathematical operation but I do not know how.   String newResult = Double.toString(result); // converts Double into String   referenca.setDisplay(newResult); //sets display to a new result   }```

My problem is that I do not know how to do this: When I type first number and a mathematical operation that number is saved into variable numStringToDouble and so is mathematical operation saved into matOperacija (not sure what type should I use int or String or Char) and then when I type number two and press equal number on the display should be added, multiplyed etc. whit the number saved in a variable numStringToDouble. My biggest problem is that I do not know how to deal with mathematical operations. How to save them and how to use them.

I tried to follow SSCCE but if I made a mistake please feel free to point out that mistake. :cool:

Thanks :)>-
• June 26th, 2012, 05:28 AM
Dr.Code
Re: Calculator
You just have to make alot of if and else if statements to calculate what math operator you should use.
Expecting that you have two values(one that has been varified earlier(when you press the plus button), par1, and one that you get from the TextField(or whatever you are using), par2) that you want to calculate you can use this example.

EXAMPLE:

Code :

```else if (src == buttonEqual) { double result; double par2 = Double.parseDouble(referenca.getDisplay()); if (mathOperator.equals("+")) { //checks if the String that holds the math operator equals "+" result = par1 + par2; } else if (mathOperator.equals("-")) { result = par1 - par2; } //Continue the else if statements for all your math operators.   referenca.setDisplay(Double.toString(result)); }```

Hope this helps!
• June 26th, 2012, 05:54 AM
ikocijan
Re: Calculator
THANK YOU,VERY MUCH!! :D that really helped.

Code :

`(mathOperator.equals("-"))`

this line is what was bothering me and now I know how to check if string is equal to something. :cool: