Java Assignment Evaluate the postfixSolutionimport javautil
Java Assignment
Evaluate the postfix
Solution
import java.util.*;
public class EvaluatePost {
public static void main(String[] args) {
// example call for evaluating the postfix
System.out.println(toPostfix(\"6 10 5 / 1 - *\"));
}
//method to evaluate postfix
public static int toPostfix(String exp) {
Stack<Integer> st = new Stack<Integer> ();
Scanner tokens = new Scanner(exp);
while (tokens.hasNext()) {
if (tokens.hasNextInt()) {
st.push(tokens.nextInt()); //pushing all the integers into stack
} else {
int b = st.pop(); //popp two integers at a time
int a = st.pop();
String op = tokens.next(); //now pop the tokens one by 1 nd perform operation
if (op.equals(\"+\")) {
st.push(a + b); //push every time the resulted value on top.
} else if (op.equals(\"-\")) {
st.push(a - b);
} else if (op.equals(\"*\")) {
st.push(a * b);
} else {
st.push(a / b);
}
}
}
return st.pop(); //return the resulted value
}
}
...........example output\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'
6
![Java Assignment Evaluate the postfixSolutionimport java.util.*; public class EvaluatePost { public static void main(String[] args) { // example call for evaluat Java Assignment Evaluate the postfixSolutionimport java.util.*; public class EvaluatePost { public static void main(String[] args) { // example call for evaluat](/WebImages/27/java-assignment-evaluate-the-postfixsolutionimport-javautil-1070808-1761560876-0.webp)