Note that there are some explanatory texts on larger screens.

plurals
  1. POFirst Java program (calculator) problems
    text
    copied!<p>I'm in the process of learning Java and my first project is a calculator, however I've run into a snag. I'm trying to get my calculator to let me enter a number then click an operator (+, -, x, /), enter another number then hit an operator again and have the display update and be able to keep this going.</p> <p>Example, I would like to be able to hit the following and have it display the total each time I hit an operator after the first:</p> <blockquote> <p>a + b / c - d = </p> </blockquote> <p>The code I have seems (to me) like it should work but it doesn't. What am I doing wrong?</p> <p>The following is the code I'm using when you hit an operator. By default wait is set to false. After running through the class once, value1 is stored and wait is set to true and that works fine. From there it doesn't seem to work quite right:</p> <pre><code>class OperatorListener implements ActionListener { public void actionPerformed(ActionEvent event) { String input = event.getActionCommand(); // Set display as string String s = display.getText(); if (!wait) { // Convert first input string to double try { value1 = Double.valueOf(s.trim()).doubleValue(); } catch (NumberFormatException nfe) { System.out.println("NumberFormatException: " + nfe.getMessage()); } dec = false; } else { // Convert second input string to double try { value2 = Double.valueOf(s.trim()).doubleValue(); } catch (NumberFormatException nfe) { System.out.println("NumberFormatException: " + nfe.getMessage()); } // Determine operation to be performed if (operator == "add") { value1 = Operators.add(value1, value2); } else if (operator == "subtract") { value1 = Operators.subtract(value1, value2); } else if (operator == "multiply") { value1 = Operators.multiply(value1, value2); } else if (operator == "divide") { value1 = Operators.divide(value1, value2); } // Convert final value to string and display display.setText(Double.toString(value1)); dec = false; } // Determine operator hit if (input.equals("+")) { operator = "add"; } else if (input.equals("-")) { operator = "subtract"; } else if (input.equals("x")) { operator = "multiply"; } else if (input.equals("/")) { operator = "divide"; } // Set wait wait = true; } } </code></pre> <p>EDIT: Updated code to fix some confusion and update the if statement. Even after this the same problem still exists. Also, the full source is available <a href="http://www.chriskankiewicz.com/documents/java/development/Calculator/src/Calculator.java" rel="nofollow noreferrer">here</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload