-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPNStackCalculator.java
81 lines (68 loc) · 2.35 KB
/
RPNStackCalculator.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
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.util.*;
public class RPNStackCalculator {
private static Stack<Integer> stack = new Stack<Integer>();
public static void main (String[]args) {
String rpnExpression;
int result;
Scanner input = new Scanner(System.in);
RPNStackCalculator calculator = new RPNStackCalculator();
System.out.println("Enter a RPN expression:");
rpnExpression = input.nextLine();
Lexer lexer = new Lexer(rpnExpression);
while (!lexer.isExausthed()) {
System.out.printf("Token [type=%s, lexeme=%s]\n", lexer.currentToken(), lexer.currentLexema() );
lexer.moveAhead();
}
if (lexer.isSuccessful()) {
result = calculator.calculateRPNExpr(rpnExpression);
System.out.println(result);
} else {
System.out.println(lexer.errorMessage());
}
}
// le a entrada char por char
public int calculateRPNExpr(String expr) {
int x, y;
int result = 0;
String nextChar;
Scanner parse = new Scanner(expr);
while(parse.hasNext()) {
nextChar = parse.next();
// se for valor, push na stack
// se for operador, pop os dois ultimos da stack para calcular
if (!isOperator(nextChar)) {
stack.push(new Integer(Integer.parseInt(nextChar)));
} else {
y = (stack.pop().intValue());
x = (stack.pop().intValue());
result = calculateSimpleExpr(nextChar.charAt(0), x, y);
stack.push(result);
}
}
return result;
}
public int calculateSimpleExpr(char operator, int x, int y) {
int total = 0;
switch (operator) {
case '+':
total = x + y;
break;
case '-':
total = x - y;
break;
case '*':
total = x * y;
break;
case '/':
total = x / y;
break;
case '%':
total = x % y;
break;
}
return total;
}
public boolean isOperator(String operator) {
return ( operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%") );
}
}