-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathInterpreterLesson.java
More file actions
76 lines (66 loc) · 2.13 KB
/
Copy pathInterpreterLesson.java
File metadata and controls
76 lines (66 loc) · 2.13 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
package patterns.behavioral;
import java.util.Stack;
public class InterpreterLesson {
public static void main(String[] args) {
String expression = "1+2+3-4";
Evaluator sentence = new Evaluator(expression);
System.out.println(sentence.interpret(sentence));
}
}
interface Expression {
int interpret(Expression context);
}
class Number implements Expression {
int number;
public Number(int number) {
this.number = number;
}
@Override
public int interpret(Expression context) {
return number;
}
}
class Plus implements Expression {
Expression leftOperand;
Expression rightOperand;
public Plus(Expression leftOperand, Expression rightOperand) {
this.leftOperand = leftOperand;
this.rightOperand = rightOperand;
}
@Override
public int interpret(Expression context) {
return leftOperand.interpret(context) + rightOperand.interpret(context);
}
}
class Minus extends Plus {
public Minus(Expression leftOperand, Expression rightOperand) {
super(leftOperand, rightOperand);
}
@Override
public int interpret(Expression context) {
return leftOperand.interpret(context) - rightOperand.interpret(context);
}
}
class Evaluator implements Expression {
private Expression syntaxTree;
Stack<Expression> expressions = new Stack<>();
public Evaluator(String expression) {
expression = new StringBuilder(expression).reverse().toString();
for(String s : expression.split("\\D")) {
expressions.push(new Number(Integer.parseInt(s)));
}
expression = new StringBuilder(expression).reverse().toString();
for(String s : expression.split("\\d")) {
if(s.equals("+")) {
expressions.push(new Plus(expressions.pop(), expressions.pop()));
} else if(s.equals("-")) {
expressions.push(new Minus(expressions.pop(), expressions.pop()));
}
}
syntaxTree = expressions.pop();
}
@Override
public int interpret(Expression context) {
return syntaxTree.interpret(context);
}
}