Skip to content
Advertisement

Java Calculator program issue

I am trying to develop a calculator program that inputs an arithmetic expression of the form number operator number = and computes the result of the expression. The expression will be evaluated from left to right not considering regular operator precedence. For example, the expression 14 - 5 * 3 = will produce 27.0. The value = displays the final result and terminates the program.

I’ve been trying to fix this for a couple of days now, but it outputs the wrong answer whenever I enter an expression with more than two numbers. For instance, 2.8 + 2 - 9.5 should equal -4.7 but the program outputs -6.7. Any idea why that is the case?

JavaScript

Advertisement

Answer

In order to make it work, try to:

  • in your 2nd switch statement, change num2 = num1 + num2; into num1 = num1 + num2;. Do this for all cases;
  • I added an isOperator boolean to skip computing the operation if input is an operator.

Full code below:

JavaScript

Edit: As mentioned in the comments, the code does not treat the cases when the user inputs 0. Below, I removed the if(num1 == 0) and if (num1 != 0 && num2 != 0) conditions:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement