Write a program that will take a string, parse it, and then calculate the value in post-fix (reverse polish) notation. To understand this mostly every expression you’ve seen in math is called in-fix notation.

In-fix Example:
3 + 2
However in post-fix notation the operator is at the end of the expression.
Post-fix Example:
3 2 +

Respuesta :

Answer and Explanation:

/**POSTFIX CALCULATION IN JAVA ****/

import java.io.*;

import java.util.*;

import java.lang.*;

public class ReversePolishIMP

{    

//main

    public static void main(String[] args)

    {

    //DECLARE VARIABLE

         int opnd1;

       int opnd2;

       int rst=0;

         //SCANNER TO READ POSTFIX STRING

       Scanner revScan=new Scanner(System.in);

         String postFix;

         //ASK REPEATEDLY

         while(true)

         {

             System.out.println("Enter a reverse polish expressio nor quit to quit");

             postFix=revScan.nextLine();

             //CHAECK FOR PROGRAM quit

             if(postFix.equals("quit"))

             {

                  System.out.println("Goodbye");

                  break;

             }

             //CREATE STACK TO STORE OPERANDS

             Stack<String> stringStack=new Stack<String>();

             //SPLIT THE STRING

             String[] t = postFix.split(" ");

             //PROCESS POSTFIX

             for(int k = 0; k < t.length; k++)

             {

                  String tok = t[k];

                  //FIND OPERAND

                  if (!"+".equals(tok) && !"*".equals(tok) && !"-".equals(tok) && !"/".equals(tok))

                       stringStack.push(tok);

                  else

                  {

                  //PERFORM ADDITION, SUBTRACTION,MULTIPLICCATION,DIVISION

                       String calOptr = t[k];

                       opnd1 = Integer.parseInt(stringStack.pop());

                       opnd2 = Integer.parseInt(stringStack.pop());

                       if (calOptr.equals("/"))

                            rst = opnd1 / opnd2;

                       else if(calOptr.equals("*"))

                            rst = opnd1 * opnd2;

                       else if(calOptr.equals("+"))

                            rst = opnd1 + opnd2;

                       else if(calOptr.equals("-"))

                            rst = opnd2 - opnd1;

                       else System.out.println("Illeagal symbol");

                       //STORE RESULT IN STACK

                       stringStack.push(Integer.toString(rst));

                  }  

             }

             //GET FINAL RESULT

             rst=Integer.parseInt(stringStack.pop());

             //CHECK FOR EMPTY STACK

             if(!stringStack.isEmpty())

             {

             System.out.println("THIS WAS NOT PROPERLY FORMATTED");

             System.out.println("0");

             }

             else

             System.out.println(rst);

         }

    }

}