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

JAVAJAVAJAVAJAVA PLEASE ADD COMMENTS AND PRINT RESULT Objective: Write a program

ID: 3664840 • Letter: J

Question

JAVAJAVAJAVAJAVA

PLEASE ADD COMMENTS AND PRINT RESULT

Objective:

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 +

A stack is used to calculate values in post-fix notation. Numbers are pushed onto the stack, and when an operator is reached it pops off the last two numbers and then pushes the resulting value back on the stack. See these EXAMPLE SLIDES for further information.

This program must:

Calculate values using the algorithm mentioned above and in the slides for addition, subtraction, multiplication, and division (+,-,*,/)

Error message if the user tries to divide by zero

Take in a string and process each digit and operator one at a time assuming white space delimits each

Make sure to check if there’s at least two items on the stack before when an operator is encountered or else it’s not a properly formatted post-fix expression

Finish when the program reaches the end of the string and it has only one value left on the stack, then that value is popped off and returned. Otherwise it was not properly formatted

Use your own created stack and not java’s built in stack

You may use any implementation so either an array or a linked structure.

HINTS! First when you’re processing the inputted string you can use a Scanner and call the method next() to get each token. From there you can evaluate if that token is an operator, numeric value, or an error. If it’s a numeric value then you may parse that string using Integer.parseInt() to get the integer value. You may also call Integer.parseInt() in a try-catch block. If the token is not an integer an exception will be raised and should be immediately halted.

Example Dialog:

Enter a reverse polish expression or "quit" to quit

3 2 +

5

Enter a reverse polish expression or "quit" to quit

5 1 2 + 4 * + 3 -

14

Enter a reverse polish expression or "quit" to quit

2 3 4 +

This was not properly formatted

0

Enter a reverse polish expression or "quit" to quit

quit

Goodbye

Explanation / Answer

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class postfix
{
   public static int evaluate(String[] tokens, int size)// implementation of the given algorithm
   {

       int returnValue = 0;

       String operators = "+-*/";

       Stack<String> stack = new Stack<String>();
       int i = 0;
       for (i = 0; i < size; i++)
       {
           String t = tokens[i];
           if (!operators.contains(t))
           {
               stack.push(t);// if token is not operator then push the digit into the stack
           }
           else
           // if the token is opertor then pop the top 2 value in stack and apply the operation
           {
               int a = Integer.valueOf(stack.pop());
               int b = Integer.valueOf(stack.pop());
               int index = operators.indexOf(t);
               switch (index)
               {
                   case 0:
                       stack.push(String.valueOf(a + b));
                       break;
                   case 1:
                       stack.push(String.valueOf(b - a));
                       break;
                   case 2:
                       stack.push(String.valueOf(a * b));
                       break;
                   case 3:
                       if (a == 0)
                       {

                           return -2000;
                       }
                       stack.push(String.valueOf(b / a));
                       break;
               }
           }
       }

       returnValue = Integer.valueOf(stack.pop());// in the last top value is result
       if (!stack.isEmpty())// if stack is not empty then improper return the code of improper format
       {

           return -1000;
       }
       return returnValue;

   }

   public static void main(String args[]) throws Exception
   {
       /* Read input from stdin and provide input before running */
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String line = "";
       while (line != "quit")// execute the loop while user enter quit
       {
           System.out.println("Enter a reverse polish expression or "q" to quit");
           line = br.readLine();
           // System.out.println(line);
           if (line.equals("quit"))
           {
               System.out.println("Goodbye");

               break;

           }

           StringTokenizer st = new StringTokenizer(line);
           String[] tokens = new String[20];
           int i = 0;
           while (st.hasMoreTokens())
           {
               // System.out.println(st.nextToken());
               tokens[i] = st.nextToken();
               // System.out.println(tokens[i]);
               i++;
           }

           /* System.out.println(j); while (i < j) { System.out.println(tokens[i]); i++; } */
           int val = evaluate(tokens, i);
           if (val == -1000)// -1000 is the error code of message not properly formatted
           {
               System.out.println("This was not properly formatted");
           }
           else if (val == -2000)// -2000 is the error code of divide by zero error
           {
               System.out.println("the denominator should not be 0");
           }
           else
               System.out.println(val);
       }
       br.close();
   }
}