When executing 1 + 2 + 3, your current code executes:
User tap on '1' '+' op1 = 1.0, action = '+' User tap on '2' '+' op1 = 2.0, action = '+' User tap on '3' '=' op1 = 2.0, op2 = 3.0, action = '+' doCal() displays the result of op1 + op2 which is 5
I think you should use op1 to store the values of previous calculations in order to get the expected behavior.
This is how I do it.
Instead of calling doCal() only when you press the equal, call it every time the statement is pressed, at the beginning of the operator’s action handler. Save the value inside op2 to enable the calculation:
void bPlusPressed(ActionEvent e) { op2 = Double.parseDouble(t.getText()); doCal(); b = true; action = '+'; }
(apply the same changes to other operators).
Inside doCal() save the result in op1 instead of displaying it:
void doCal() { // No need to use a class attribute for result, prefer a local variable. final double result; switch (action) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/': result = op1 / op2; break; // When no action is set, simply copy op2 into op1 default: result = op2; } op1 = result; }
Then change bEqPressed() to display op1 and reset the value of action :
void bEqpressed(ActionEvent e) { op2 = Double.parseDouble(t.getText()); doCal(); t.setText(String.valueOf(result)); action = '\0'; }
That should do the trick.
source share