-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntParser.java
More file actions
74 lines (61 loc) · 2.03 KB
/
IntParser.java
File metadata and controls
74 lines (61 loc) · 2.03 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
package com.company;
public class IntParser {
String expression;
int currentPos = -1;
int currentChar;
public IntParser(String expression) {
this.expression = expression;
}
void setExpression(String expression){
this.expression = expression;
}
private void nextChar(){
currentChar = (++currentPos < expression.length()) ? expression.charAt(currentPos) : -1;
}
private boolean eat(int ch){
while (currentChar == ' ') nextChar();
if (currentChar == ch) {
nextChar();
return true;
}
return false;
}
int evaluate() {
nextChar();
int x = prsExpression();
if (currentPos < expression.length()) throw new RuntimeException("Unexpected: " + (char)currentChar);
return x;
}
private int prsExpression() {
int x = prsTerm();
for (;;) {
if (eat('+')) x += prsTerm();
else if (eat('-')) x -= prsTerm();
else return x;
}
}
private int prsTerm() {
int x = prsFactor();
for (;;) {
if (eat('*')) x *= prsFactor();
else if (eat('/')) x /= prsFactor();
else return x;
}
}
private int prsFactor() {
if (eat('+')) return prsFactor();
if (eat('-')) return -prsFactor();
int x;
int startPos = currentPos;
if (eat('(')) {
x = prsExpression();
eat(')');
} else if (currentChar >= '0' && currentChar <= '9') {
while (currentChar >= '0' && currentChar <= '9') nextChar();
x = Integer.parseInt(expression.substring(startPos, currentPos));
} else {
throw new RuntimeException("Unexpected: " + (char)currentChar);
}
return x;
}
}