Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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 ... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Management Accounting Information for Decision-Making and Strategy Execution

Authors: Anthony A. Atkinson, Robert S. Kaplan, Ella Mae Matsumura, S. Mark Young

6th Edition

137024975, 978-0137024971

More Books

Students also viewed these Programming questions