Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

classroom msstateedu X X My board Content x y D Postri No x C Secure I https myc

ID: 3805569 • Letter: C

Question

classroom msstateedu X X My board Content x y D Postri No x C Secure I https mycoul es.msstate.edu/ bbcswebdav pid-1085319-dt-content-rid-6693448 1/courses/lgr 1.201710 Group01/Postfix%20Notation pdf perform operations as soon as they are entered. In this lab you will write a program that evaluates an expression entered in postfix notation. Instructions: You will be implementing the Stack class from your lecture class to assist with the evaluation of the postfix expression, if you haven't already finished it. Your Stack class will need to accommodate the following operations (from the slides): Initialize the Stack Destroy the Stack Is Stack Empty ls Stack Full Push Pop Top en -str. You may assume that only the four basic math operations A,/) are used in the expression each operation or integer will be surrounded by a least 1 space oneach side a Ask me any 1100 AM 3/2/20

Explanation / Answer

Here is the java code to evaluate the postfix expression

import java.util.*;

public class PostEval
{
public static void main(String[] args)
{
System.out.println("Enter the postfix expression ");
Scanner scan=new Scanner(System.in);
String ip= scan.nextLine();
System.out.println(postfixeval(ip));   
}
  
public static int postfixeval(String exp) {
      Stack<Integer> s = new Stack<Integer> ();
       Scanner part = new Scanner(exp);
      
       while (part.hasNext())
       {
      
           if (part.hasNextInt())
           {
               s.push(part.nextInt());
           }
           else
           {
               int num2 = s.pop();
               int num1 = s.pop();
               String op = part.next();
              
               if (op.equals("+"))
               {
                   s.push(num1 + num2);
               }
               else if (op.equals("-"))
               {
                   s.push(num1 - num2);
               }
               else if (op.equals("*"))
               {
                   s.push(num1 * num2);
               }
               else
               {
                   s.push(num1 / num2);
               }
              
           }
       }
       return s.pop();
}
}