 naz-mul
4/22/2015 - 10:38 PM

## Lab7 Q5 OOP3

Lab7 Q5 OOP3

``````package lab7;

import java.util.Scanner;
import java.util.Stack;

/**
* 5.	Reverse Polish Notation
Consider how you write the expression (3+4)*5.
You can eliminate the parentheses if you write the operators after the numbers like this: 3 4 + 5 *.
This is known as Reverse Polish Notation and allows computation of the expression by reading the
expression from left to right. An algorithm for implementing this approach using a stack is as follows:
The algorithm for reverse polish notation is:
Pop two values off the stack,
Combine the two values off the stack,
Push the result back onto the stack,
Else if there is no more input,
Pop and display the result.
Else If you read a number,
Push it on to the stack,

Write java code to implement this algorithm.

Enter expression in Reverse Polish Notation/Q to quit
57
5
+
2
/
Quit
Total is: 32
*/
public class ReversPolishNotation {

public static void main(String[] args) {
Stack<String> polish = new Stack<String>();
String s = "";
double num1 = 0, num2 = 0, total = 0;
Scanner in = new Scanner(System.in);

do {
s = in.next();

// Check if the input has a operator
if (s.equals("+") || s.equals("-") || s.equals("/")
|| s.equals("*")) {

switch ((String) s) {
case "+":
num1 = Double.parseDouble(polish.pop());
num2 = Double.parseDouble(polish.pop());
total = num1 + num2;
polish.push(String.valueOf(total));
break;

case "-":
num1 = Double.parseDouble(polish.pop());
num2 = Double.parseDouble(polish.pop());
total = num1 - num2;
polish.push(String.valueOf(total));
break;

case "/":
num1 = Double.parseDouble(polish.pop());
num2 = Double.parseDouble(polish.pop());
total = num2 / num1;
polish.push(String.valueOf(total));
break;

case "*":
num1 = Double.parseDouble(polish.pop());
num2 = Double.parseDouble(polish.pop());
total = num1 * num2;
polish.push(String.valueOf(total));
break;
}// end of switch

} else if (isNumeric(s)) { // if it's a number push it to the stack
polish.push((String) s);

} else if (s.equalsIgnoreCase("Q")) // if there aren't any more input
System.out.println("Total is: " + polish.pop());

//System.out.print(polish.toString());

} while (!s.equalsIgnoreCase("Q"));
// close scanner
in.close();
}

public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
}
``````