-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluatePostfix.java
More file actions
44 lines (38 loc) · 1.3 KB
/
Copy pathEvaluatePostfix.java
File metadata and controls
44 lines (38 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;
public class EvaluatePostfix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter PostFix :");
String PostFix = sc.nextLine();
Stack<Integer> st = new Stack<>();
for (int i = 0; i < PostFix.length(); i++) {
char next = PostFix.charAt(i);
if (next >= 48 && next <= 57) {
st.push(Integer.parseInt(next + ""));
} else {
int ope1 = st.pop();
int ope2 = st.pop();
switch (next) {
case '+':
st.push(ope1 + ope2);
break;
case '-':
st.push(ope2 - ope1);
break;
case '*':
st.push(ope1 * ope2);
break;
case '/':
st.push(ope2 / ope1);
break;
case '^':
st.push((int) Math.pow(ope1, ope2));
break;
}
}
System.out.println("Final Answer :" + st);
}
System.out.println("Popped Answer :" + st.pop());
sc.close();
}
}