Write a Java program to implement the postfix evaluation algorithm given below u
ID: 3574744 • Letter: W
Question
Write a Java program to implement the postfix evaluation algorithm given below using a Java API Stack data structure. Your program must be able to accept the expression as a command-line argument. Test your program with following Expressions: (all expressions contains single digit integers)
5 3 + 2 * 3 / 6 - 4 +
8 3 / 6 + 3 -
3 5 * 3 / 6 + 3 * -
Make an empty stack.
While not at end of expression.
read a character from input
if input char is an operand, then
push it on to the stack.
end if
if input char is an operator, then
pop the top two operands off the stack, perform the operation, place the result on stack.
endif
endwhile
if stack is empty
report an error
else
pop the stack and report the results
endif
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
Please do not put any space in postfix expression while passing from command line.
import java.io.IOException;
import java.util.Stack;
public class PostfixEvaluator {
public int evaluate(char[] postfix) {
int n, r = 0;
n = postfix.length;
Stack<Integer> a = new Stack<Integer>();
for (int i = 0; i < n; i++) {
char ch = postfix[i];
if (ch >= '0' && ch <= '9')
a.push(ch - '0');
else if (ch == ' ')
continue;
else {
int x = a.pop();
int y = a.pop();
switch (ch) {
case '+':
r = x + y;
break;
case '-':
r = y - x;
break;
case '*':
r = x * y;
break;
case '/':
r = y / x;
break;
default:
r = 0;
}
a.push(r);
}
}
r = a.pop();
return (r);
}
// main method
public static void main(String[] args)throws IOException
{
// declaring object
PostfixEvaluator postfixEval = new PostfixEvaluator();
if(args == null){
System.out.println("Please pass postfix expression from command line");
}else{
String postfix = args[0];
postfix = postfix.trim();
System.out.println("Postfix Expression:- "+postfix);
System.out.println("Evaluated value of postfix: "+postfixEval.evaluate(postfix.toCharArray()));
}
}
}
/*
Sample output:
Postfix Expression:- 53+2*3/6-4+
Evaluated value of postfix: 3
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.