-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathExercise1311_EvaluatePostfix.java
37 lines (37 loc) · 1.25 KB
/
Exercise1311_EvaluatePostfix.java
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
public class Exercise1311_EvaluatePostfix {
public static void main(String[] args) {
Stack<String> ops = new Stack<String>();
Stack<Double> vals = new Stack<Double>();
while (!StdIn.isEmpty())
{
String s = StdIn.readString();
if (s.equals("("));
else if (s.equals("+"))
ops.push(s);
else if (s.equals("-"))
ops.push(s);
else if (s.equals("*"))
ops.push(s);
else if (s.equals("/"))
ops.push(s);
else if (s.equals("sqrt")) ops.push(s);
else if (s.equals(")"))
{
String op = ops.pop();
double v = vals.pop();
if (op.equals("+"))
v = vals.pop() + v;
else if (op.equals("-"))
v = vals.pop() - v;
else if (op.equals("*"))
v = vals.pop() * v;
else if (op.equals("/"))
v = vals.pop() / v;
else if (op.equals("sqrt")) v = Math.sqrt(v);
vals.push(v);
}
else vals.push(Double.parseDouble(s));
}
StdOut.println(vals.pop());
}
}