In: Computer Science
Write a program that will recognize and evaluate prefix expressions. First design and implement a class of prefix expressions. This class should contain methods to recognize and evaluate prefix expressions. This chapter discusses the algorithms you will need to implement these methods. Walls and Mirrors 3rd edition Chapter 6 Programming Practice 8. Programming Language: Java.
//Create a class in java Name as PrefixExpressionEvaluator.java
import java.util.Stack;
public class PrefixExpressionEvaluator{
public static void main(String[] args) {
String expression = "+8*68";
//check for valid expression first and then perform
evaluatePrefixExpression(expression);
}
static Boolean isNumber(char ch) {
// check for character is operand or not
if (ch >= 48 && ch <= 57) {
return true;
} else {
return false;
}
}
public static void evaluatePrefixExpression(String expression) {
try {
//import stack from java.util
Stack<Double> stk = new Stack<Double>();
for (int j = expression.length() - 1; j >= 0; j--) {
// Push operand to Stack
if (isNumber(expression.charAt(j))) {
stk.push((double) (expression.charAt(j) - 48));
} else {
// Operator encountered
// Pop two elements from Stack
double operand1 = stk.peek();
stk.pop();
double operand2 = stk.peek();
stk.pop();
//perform operation
switch (expression.charAt(j)) {
case '+':
stk.push(operand1 + operand2);
break;
case '-':
stk.push(operand1 - operand2);
break;
case '*':
stk.push(operand1 * operand2);
break;
case '/':
stk.push(operand1 / operand2);
break;
}
}
}
System.out.println(expression + "= " + stk.peek());
} catch (Exception e) {
System.out.println("Not valid Prefix Expression");
}
}
}
//output
+8*68= 56.0
//invalid expression
-+8*68 is Not valid Prefix Expression