Question

In: Computer Science

IN JAVA PLZ follow all directions SHOW OUPUT! Write class PostfixEvaluator that evaluates a postfix expression...

IN JAVA PLZ follow all directions SHOW OUPUT! Write class PostfixEvaluator that evaluates a postfix expression such as 6 2 + 5 * 8 4 / -

The program should read a postfix expression consisting of single digits and operators into a StringBuilder, The program should read the expression and evaluate it (assume it's valid). The algorithm to evaluate a postfix expression is shown below. Use +, -, *, /, and ^. ^ is the exponent.

Append a right parenthesis ') ' to the end of the postfix expression. When the right-parenthesis character is encountered, no further processing is necessary.

Until the right parenthesis is encountered, read the expression from left to right.

if the current character is a digit, do the following:

Push its integer value onto the stack

else, if the current character is an operator:

Pop the two top elements of the stack into variables x and y.

Calculate y operator x.

Push the result of the calculation onto the stack.

End until when the right parenthesis is encountered in the expression,

Pop the top value of the stack. This is the result of the postfix expression .

[Note: (based on the sample expression at the beginning of this exercise), if the operator is '/', the top of the stack is 4 and the next element in the stack is 40, then pop 4 into x, pop 40 into y, evaluate 40 / 4 and push the result, 10, back on the stack. This note also applies to other operators.] The arithmetic operations allowed in an expression are: + (addition), - (subtraction), '' (multiplication),/ (division), A (exponentiation) and x (remainder).

You willy want to use the following methods:

a) Method evaluatePostfixExpression, which evaluates the postfix expression. It is called from main. (20)

b) Method calculate, which evaluates the expression opl operator op2. Called from evaluatePostfixExpression. (20)

c) Method printStack which prints out the stack after each push or pop. Called from evaluatePostfixExpression (multiple times) (20)

This example can all be done in a single class.

The main program simply request the postfix expression. Remember to leave a space between each digit and/or operator. (10)

Sample input/output

Please enter a postfix expression:

6 2 + 5 * 8 4 / -

The original postfix expression is:

6 2 + 5 * 8 4 / -

6

6

2

6

8

8

5

8

40

40

8

40

8

4

40

8

40

40

2

40

38

The value of the expression is: 38

Another Example:

Please enter a postfix expression:

4 5 + 3 / 4 ^ 2 -

The original postfix expression is:

4 5 + 3 / 4 ^ 2 -

4

4

5

4

9

9

3

9

3

3

4

3

81

81

2

81

79

The value of the expression

Solutions

Expert Solution

import java.util.*;
import java.util.Stack;
class PostfixEvaluation 
{//String to store input expression
    String postfix;
    //Stack to perform postix evaluation
    Stack<char[]> stk=new Stack<char[]>();
    //Function to display stack elements
     void printStack()
    {
        //Accessing each node in stack
        for(int i=0;i<this.stk.size();i++)
        {
            //Converting it to int
            int r=Integer.parseInt(String.valueOf(this.stk.get(i)));
         System.out.println(r);   
        }
            
    }
    //Calculating arithmatic operation
    void calculte(int x,char op,int y)
    {
        
        int r=0;
        //Switch to prform arithmatic operation
        switch (op)
        {
            case '+':  r=x+y;
                        break;
            case '*':  r=x*y;
                        break;
            case '-': r=x-y;
                        break;
           case '/': r=x/y;
                        break;   
           case '%': r=x%y;
                    
                        break;      
            
        }
        //Converting integer to character array
        char[] r1=(String.valueOf(r).toCharArray());
        //Pushing result to top of stack 
        this.stk.push(r1); 
        //Printing stack values
        this.printStack();
        
    }
    public void evaluatePostfixExpression()
    {
        int i=0,res=0;
        //Loop to access input string 
        while(this.postfix.charAt(i)!=')')
        {
            
            //Getting input character at ith place
            char c=this.postfix.charAt(i);
            //Checking if input character is a digit
            if(Character.isDigit(c))
            {
                //Pushing c to top of stack 
                this.stk.push(String.valueOf(c).toCharArray());
                //Printing stack values
                this.printStack();
            }
            else if(c!=' ')
            {
               //Popping the top elemnt of stack
                int y=Integer.parseInt(String.valueOf(this.stk.pop()));
                //Printing stack values
                this.printStack();
                //Popping the top elemnt of stack
                int x=Integer.parseInt(String.valueOf(this.stk.pop()));
                //Printing stack values
                this.printStack();
                //Calling function caculate()
                this.calculte(x, c, y);
            }
            //storing  result
            res=Integer.parseInt(String.valueOf(this.stk.peek()));
            i++;
        }
         //Printing final result
        System.out.println("The value of the expression is: "+res);
    }
public static void main(String[] args)
 {
     //Creating instance of class PostfixEvaluation
    PostfixEvaluation p=new PostfixEvaluation();
    //Reading input
    System.out.println("Enter postfix Expression:");   
    Scanner myObj = new Scanner(System.in);
    p.postfix=myObj.nextLine();
    System.out.println("The original postfix expression is: "+p.postfix);
    p.postfix+=')';
    //Calling function evaluatePostfixExpression();
    p.evaluatePostfixExpression();
}
}

SAMPLE OUTPUT


Related Solutions

Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2...
Postfix Evaluation (JAVA PROGRAMMING) Write class PostfixEva1uator that evaluates a postfix expression such as 6 2 + 5 * 8 4 / - The program should read a postfix expression consisting of single digits and operators into a StringBuilder, The program should read the expression and evaluate it (assume it's valid). The algorithm to evaluate a postfix expression is shown below. Use +, -, *, /, and ^. ^ is the exponent. Append a right parenthesis ') ' to the...
For this assignment you will write a class that transforms a Postfix expression (interpreted as a...
For this assignment you will write a class that transforms a Postfix expression (interpreted as a sequence of method calls) into an expression tree, and provides methods that process the tree in different ways. We will test this using our own program that instantiates your class and calls the expected methods. Do not use another class besides the tester and the ExpressionTree class. All work must be done in the class ExpressionTree. Your class must be called ExpressionTree and have...
Using Java 8. Write a program that reads an expression in postfix notation, builds the expression...
Using Java 8. Write a program that reads an expression in postfix notation, builds the expression tree and prints the expression in prefix and infix notation and evaluates the expression. (Hint use a stack)
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are...
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are from a file "in.dat". The file contains a sequence of infix form expressions, one per line. The character '$' is an end mark. For example, the following file has four infix form expressions: 1 + 2 * 3 ^ ! ( 4 == 5 ) $ 3 * ( 6 - 4 * 5 + 1) + 2 ^ 2 ^ 3 $ 77...
Write a class Lab7 that reads and evaluates postfix expressions contained in a file. Each line...
Write a class Lab7 that reads and evaluates postfix expressions contained in a file. Each line of the file contains a postfix expression with integers as operands and ‘+’, ‘-’, ‘*’ and ‘/’ as operators. Consecutive operands and operators are separated by spaces. Note the following requirements for the lab: • The main method in Lab7.java should do the following. 1. ask the user for the name of the file containing the expressions, 2. for each line of the file,...
write a java program tht evaluates postfix expressions. args[0] = the output file the answer will...
write a java program tht evaluates postfix expressions. args[0] = the output file the answer will print to
Write a class PostFix that has one method covert that converts an infix expression (as a...
Write a class PostFix that has one method covert that converts an infix expression (as a string input) to a postfix. Then Test it in a different class. code in java.
Write a program that takes an infix expression as input and produces a postfix expression. The...
Write a program that takes an infix expression as input and produces a postfix expression. The infix and postfix expressions are in the form of vectors of strings. We will test with a main method that takes a file name as input from the command line. We will test your implementation using printPostFix() method.   There are sample input and output files in this folder. You may edit the header file. Example 1 infix expression = apple + banana * cat...
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a program that converts prefix expressions to postfix and postfix expressions to prefix. (java) The...
Write a program that converts prefix expressions to postfix and postfix expressions to prefix. (java) The program for this project should consist of three classes. -The main class should create a GUI that allows the user to input an expression in either prefix or postfix and convert it to postfix or prefix, respectively. -The other class should contain the code to perform the conversions. --->The pseudocode for prefix to postfix, which requires two stacks, is shown below: tokenize the string...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT