USING JAVA: In this assignment you are to write a Postfix evaluator program. Not
ID: 3821279 • Letter: U
Question
USING JAVA: In this assignment you are to write a Postfix evaluator program.
Note that one problem with the example given at this site is that the operands are restricted to single digit characters. In other words, the operands are restricted to 0,1,2,3,4,5,6,7,8, and 9. So operands such as 32 or 567 are not allowed on pain of getting the wrong result.
Your assignment is to write a postfix evaluator that allows multiple digit character strings as operands. You will do this by using a space character as a delimiter for operands. E.g., suppose the infix version of the expression is (10 + 320). The postfix equivalent would be 10 320+. Note the space after 10. This tells you that you have come to the end of the operand and it is 10. Your program should take a postfix expression (one that allows multiple digit character strings as operands) and outputs the result of evaluating it. With 10 320+ as input, the output would be 330.
Explanation / Answer
import java.util.Stack;
public class PostfixEvaluate {
public static void main(String[] args) {
System.out.println(postfixEvaluate("100 2+")); // 3
System.out.println(postfixEvaluate("1 2 3 * + 4 +")); // 11
System.out.println(postfixEvaluate("5 2 4 * + 7 -")); // 6
System.out.println(postfixEvaluate("2 3 + 4 5 * +")); // 25
System.out.println(postfixEvaluate("8 5 * 7 4 2 + * +")); // 82
System.out.println(postfixEvaluate("6 8 2 / 1 - *")); // 18
}
// Evaluates the given postfix expression string and returns the result.
// Precondition: expression consists only of integers, +-*/, and spaces in
// proper postfix format such as "2 3 - 4 *"
public static double postfixEvaluate(String exp) {
Stack<Double> s = new Stack<> ();
for (int i = 0; i < exp.length(); i++)
{
if (exp.charAt(i) == ' ')
continue;
// Token is a number, push it to stack
if (exp.charAt(i) >= '0' && exp.charAt(i) <= '9')
{
// There can be multi digit number. Create number as string
StringBuffer numberString = new StringBuffer();
boolean isMultiDigit = false;
while (i < exp.length() && ((exp.charAt(i) >= '0' && exp.charAt(i) <= '9') || exp.charAt(i) == '.'))
{
isMultiDigit = true;
numberString.append(exp.charAt(i++));
}
if(isMultiDigit)
{
i--;
}
s.push(Double.parseDouble(numberString.toString()));
} else
{
double num2 = s.pop();
double num1 = s.pop();
Character op = exp.charAt(i);
if (op == '+') {
s.push(num1 + num2);
} else if (op == '-') {
s.push(num1 - num2);
} else if (op == '*') {
s.push(num1 * num2);
} else {
s.push(num1 / num2);
}
// "+", "-", "*", "/"
}
}
return s.pop();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.