I need help with writing the program that reads a formula, evaluates it, and prints the result.
Question:
I need help with writing the program that reads a formula, evaluates it, and prints the result. The formula contains integers and operators, each separated by a single space. The possible operators are: + - * /. In the format used here, we will instead have the 2 operands first, and then only the operator (e.g., "5 2 +", which still means that you have to add 5 and 2 together). This notation is called "postfix". The advantage of this notation is that you no longer need to worry about the order of the operations (i.e., for example, that you should first do the * and / before doing the + and -). There is no need for parentheses anymore either. Here are more complex examples:
"6 + 10 / 2" "10 2 / 6 +"
"(6 + 10) / 2" "6 10 + 2 /"
The way to do the calculation is as follows: when you see a number, push it on a stack. When you see an operator, pop 2 numbers from the stack (second operand, and then first operand), apply the operator on those 2 operands and then push the result you got on the stack. In the end, your stack will contain only one number, and that is the final result of this calculation. I need help with writing the program that reads such a formula (as one string) from the user and prints the result on the screen. Use the Stack class. Note: you can check if string str is actually an integer using the following code: "if (str. matches("d+"))" returns true if the string contains only a sequence of digits.
Management Accounting Information for Decision-Making and Strategy Execution
ISBN: 978-0137024971
6th Edition
Authors: Anthony A. Atkinson, Robert S. Kaplan, Ella Mae Matsumura, S. Mark Young