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.
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:
a + b / c - d =
The code I have seems (to me) like it should work but it doesn't. What am I doing wrong?
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:
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;
}
}
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 here