Question
JAVA Scenario: We are used to writing mathematical expressions in the form of 1 + 2 * 3 . This type of notation is called
JAVA
Scenario: We are used to writing mathematical expressions in the form of 1 + 2 * 3. This type of notation is called an infix. Using infix notation, an operator is always in between two operands. There is a different notation called postfix, where the operator is after the operands. Examples of such expressions are shown in the following table:
Infix expression | Postfix expression |
---|---|
1 + 2 | 1 2 + |
1 + 2 * 3 | 1 2 3 * + |
(1 + 2) * 3 | 1 2 + 3 * |
5 + 4 / 2 * 3 | 5 4 2 / 3 * + |
Aim: Implement an algorithm that accepts a postfix string, evaluates it, and returns the result.
Prerequisites
-
Implement the following method:
public double evaluate(String postfix) { //... }
-
Assume the operator and operands are always separated by a space, such as "5 2 +". The input string will look like the examples shown in the preceding table
Steps for Completion
- Use the stack data structure to solve this problem.
- Start processing the expression from left to right.
- If you encounter a numeric operand, push it on the stack.
- If you encounter an operator, pop two items from the stack and perform the operation accordingly (addition, subtraction, and so on) and push the result back on the stack.
- Once you have processed the entire expression, the result should be the on the top of the stack.
REQUIRED TASKS:
Implement the evaluate() method.
Use the stack data structure to solve this problem.
Program properly evaluates operators.
GIVEN CODE:
public class EvalPostfix { // Write your code here public static void main(String[] args) { /* * This main method is a stub. * It does nothing. * Feel free to write your own code to test your implementation. * In this case, we have nothing actionable in here, just this comment block, so the JVM should rapidly lose interest and move on to the rest of your code. */ } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
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