-
Notifications
You must be signed in to change notification settings - Fork 32
/
CalculatorBaseVisitorImpl.java
79 lines (64 loc) · 2.28 KB
/
CalculatorBaseVisitorImpl.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
import java.util.HashMap;
public class CalculatorBaseVisitorImpl extends CalculatorBaseVisitor<Double> {
private HashMap<String, Double> variables = new HashMap<String, Double>();
@Override
public Double visitPlus(CalculatorParser.PlusContext ctx) {
return visit(ctx.plusOrMinus()) + visit(ctx.multOrDiv());
}
@Override
public Double visitMinus(CalculatorParser.MinusContext ctx) {
return visit(ctx.plusOrMinus()) - visit(ctx.multOrDiv());
}
@Override
public Double visitMultiplication(CalculatorParser.MultiplicationContext ctx) {
return visit(ctx.multOrDiv()) * visit(ctx.pow());
}
@Override
public Double visitDivision(CalculatorParser.DivisionContext ctx) {
return visit(ctx.multOrDiv()) / visit(ctx.pow());
}
@Override
public Double visitSetVariable(CalculatorParser.SetVariableContext ctx) {
Double value = visit(ctx.plusOrMinus());
variables.put(ctx.ID().getText(), value);
return value;
}
@Override
public Double visitPower(CalculatorParser.PowerContext ctx) {
if (ctx.pow() != null)
return Math.pow(visit(ctx.unaryMinus()), visit(ctx.pow()));
return visit(ctx.unaryMinus());
}
@Override
public Double visitChangeSign(CalculatorParser.ChangeSignContext ctx) {
return -1*visit(ctx.unaryMinus());
}
@Override
public Double visitBraces(CalculatorParser.BracesContext ctx) {
return visit(ctx.plusOrMinus());
}
@Override
public Double visitConstantPI(CalculatorParser.ConstantPIContext ctx) {
return Math.PI;
}
@Override
public Double visitConstantE(CalculatorParser.ConstantEContext ctx) {
return Math.E;
}
@Override
public Double visitInt(CalculatorParser.IntContext ctx) {
return Double.parseDouble(ctx.INT().getText());
}
@Override
public Double visitVariable(CalculatorParser.VariableContext ctx) {
return variables.get(ctx.ID().getText());
}
@Override
public Double visitDouble(CalculatorParser.DoubleContext ctx) {
return Double.parseDouble(ctx.DOUBLE().getText());
}
@Override
public Double visitCalculate(CalculatorParser.CalculateContext ctx) {
return visit(ctx.plusOrMinus());
}
}