-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exec.java
79 lines (70 loc) · 1.35 KB
/
Exec.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
package com.example;
/**
* Execute Expression
*/
class Exec {
/**
* Return the value after execution
*/
double evaluate(Expr expr) {
double result;
// BE
if (expr instanceof BE) {
result = this.l((BE) expr);
}
// GRE
else if (expr instanceof GRE) {
result = this.g((GRE) expr);
}
// I
else if (expr instanceof I) {
result = this.l((I) expr);
}
// UE
else if (expr instanceof UE) {
result = this.u((UE) expr);
}
// Unknown
else {
return -1;
}
return Double.parseDouble(
String.format("%.2f", result));
}
/**
* LiteralExpr
*/
private double l(I expr) {
return expr.val;
}
/**
* BinaryExpr
*/
private double l(BE expr) {
double x = this.evaluate(expr.L); // L
double y = this.evaluate(expr.R); // R
System.out.printf("L: %.2f \t R: %.2f \t P: %s\n", x, y, expr.P);
return switch (expr.P) { // P
case ADD -> x + y;
case SUB -> x - y;
case MUL -> x * y;
case DIV -> x / y;
};
}
/**
* GroupExpr
*/
private double g(GRE expr) {
return this.evaluate(expr.E);
}
/**
* UnaryExpr
*/
private double u(UE expr) {
if (expr.op == Op.SUB) {
return -this.evaluate(expr.expr);
} else {
throw new IllegalStateException("Unexpected value: " + expr.op);
}
}
}