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

Objective: Write a program that will populate a queue with post-fix (reverse pol

ID: 3889521 • Letter: O

Question

Objective:

Write a program that will populate a queue with post-fix (reverse polish) integer expressions and then print out the solution to each expression. 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:

Assume that each number and operator is separated by any type of space, and each expression is separated by a new line

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

Read a given file

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 queue, and not java’s built in stack and queue

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:

Welcome to the reverse Polish Calculator!

Enter in the name of the file

revPol.txt

Calculating 3 2 +

Result is 5

Calculating 5 1 2 + 4 * + 3 -

Result is 14

Calculating 2 3 4 +

Ill formatted expression

Result is 0

Calculating 0

Result is 0

Calculating 6 7 8 9 * + - 8 4 / /

Result is -36

Calculating 1 2 3 4 + - 5 6 * + +

Result is 26

Calculating 2 4 + 5 + 7 + 8 + 9 +

Result is 35

Calculating +

Ill formatted expression

Result is 0

Calculating 2 b +

Exception! For input string: "b"

Result is 0

Calculating 1 0 /

Cannot divide by 0

Result is 0

Explanation / Answer

Solution:

JAVA Code:

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Scanner;

import java.util.Stack;

public class PostfixSolution {

@SuppressWarnings("resource")

public static int postfixEvaluate(String exp) throws Exception {

Stack<Integer> stack = new Stack<Integer>();

Scanner tokens = new Scanner(exp);

String operator = "";

int operatorCount = 0;

int operantCount = 0;

while (tokens.hasNext()) {

if (tokens.hasNextInt()) {

operantCount++;

stack.push(tokens.nextInt());

} else if ((operator = tokens.next()).equals("+")

|| operator.equals("-") || operator.equals("*")

|| operator.equals("/")) {

operatorCount++;

int num1;

int num2;

try {

num2 = stack.pop();

num1 = stack.pop();

} catch (Exception e) {

throw new Exception("Ill formatted expression");

}

String op = operator;

if (op.equals("+")) {

stack.push(num1 + num2);

} else if (op.equals("-")) {

stack.push(num1 - num2);

} else if (op.equals("*")) {

stack.push(num1 * num2);

} else {

stack.push(num1 / num2);

}

} else {

throw new Exception("Exception! For input string: " + operator);

}

}

if (operatorCount == operantCount - 1)

return stack.pop();

else

throw new Exception("Ill formatted expression");

}

@SuppressWarnings("resource")

public static void main(String[] args) throws IOException {

System.out.println("Welcome to the reverse Polish Calculator!");

System.out.println("Enter in the name of the file");

Scanner sc = new Scanner(System.in);

String fileName = sc.next();

FileInputStream fstream = new FileInputStream(fileName);

DataInputStream in = new DataInputStream(fstream);

BufferedReader br = new BufferedReader(new InputStreamReader(in));

String postfix;

// Reading data from file

while ((postfix = br.readLine()) != null) {

try {

System.out.println("Calculating " + postfix);

System.out.println("Result is " + postfixEvaluate(postfix));

} catch (Exception e) {

if (e instanceof ArithmeticException)

System.err.println("cannot divide by 0");

else

System.err.println(e.getMessage());

System.out.println("Result is 0");

}

}

}

}

Let me know any concerns. Thank you.