-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfixEvaluator.java
More file actions
58 lines (51 loc) · 2 KB
/
Copy pathPostfixEvaluator.java
File metadata and controls
58 lines (51 loc) · 2 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
package project;
public class PostfixEvaluator {
private Stack stack;
public PostfixEvaluator(int stackSize) {
this.stack = new Stack(stackSize);
}
public int evaluatePostfix(String postfix) {
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix.charAt(i);
if (Character.isDigit(ch)) {
stack.push(ch - '0'); //subtrcting the ASCII number of zero(48) to get the ASCII number of our character
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^') {
if (stack.isEmpty()) {
System.out.println("Invalid Expression: Insufficient operands");
return 0;
}
int operand2 = stack.pop();
if (stack.isEmpty()) {
System.out.println("Invalid Expression: Insufficient operands");
return 0;
}
int operand1 = stack.pop();
int result = 0;
switch (ch) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '^': result = operand1 ^ operand2; break;
case '/':
if (operand2 == 0) {
System.out.println("Invalid Expression: Division by zero");
return 0;
}
result = operand1 / operand2;
break;
}
stack.push(result);
}
}
if (stack.isEmpty()) {
System.out.println("Invalid Expression: No result");
return 0;
}
int result = stack.pop();
if (!stack.isEmpty()) {
System.out.println("Invalid Expression: Extra operands");
return 0;
}
return result;
}
}