-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputePrefix.java
More file actions
81 lines (73 loc) · 2.06 KB
/
ComputePrefix.java
File metadata and controls
81 lines (73 loc) · 2.06 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
public class ComputePrefix {
private int calculateExpression (String line) {
int val, operand1, operand2;
int i;
String tmp;
Stack<String> st = new Stack<String>();
String[] params = line.split("\\s");
System.out.println("Expression is " + line);
for (i = 0; i < params.length; i++) {
if (params[i].equals("+") || params[i].equals("*") || params[i].equals("/")) {
st.push(params[i]);
} else {
tmp = st.peek();
if (tmp.equals("+") || tmp.equals("*") || tmp.equals("/")) {
st.push(params[i]);
} else {
operand1 = Integer.valueOf(st.pop()).intValue();
operand2 = Integer.valueOf(params[i]).intValue();
tmp = st.pop();
if (tmp.equals("+")) {
val=operand1 + operand2;
st.push(Integer.toString(val));
}
if (tmp.equals("*")) {
val=operand1 * operand2;
st.push(Integer.toString(val));
}
if (tmp.equals("/")) {
val=operand1/operand2;
st.push(Integer.toString(val));
}
}
}
}
while (st.size() != 1) {
operand2 = Integer.valueOf(st.pop()).intValue();
operand1 = Integer.valueOf(st.pop()).intValue();
tmp = st.pop();
if (tmp.equals("+")) {
val=operand1 + operand2;
st.push(Integer.toString(val));
}
if (tmp.equals("*")) {
val=operand1 * operand2;
st.push(Integer.toString(val));
}
if (tmp.equals("/")) {
val=operand1/operand2;
st.push(Integer.toString(val));
}
}
val = Integer.valueOf(st.pop()).intValue();
return val;
}
public ComputePrefix(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
System.out.println(calculateExpression(line));
}
}
public static void main (String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Unsupported number of parameters passed. Exiting.");
System.exit(1);
}
ComputePrefix cp = new ComputePrefix(args[0]);
}
}