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
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.
Step by Step Solution
3.42 Rating (152 Votes )
There are 3 Steps involved in it
Step: 1
Below is a simple Java program that reads a postfix formula from the user evaluates it using a stack ...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started