-
Notifications
You must be signed in to change notification settings - Fork 1
/
Calc2.java
141 lines (133 loc) · 2.53 KB
/
Calc2.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package Strings;
public class Calc2 {
static enum TOKEN {
PLUS, MINUS, MUL, DIV, NUMBER, LP, RP, END, FUNCTION;
}
double expr() {
double left = term();
while (true) {
switch (curr_tok) {
case PLUS:
left += term();
break;
case MINUS:
left -= term();
break;
default:
return left;
}
}
}
double term() {
double left = prim();
while (true) {
switch (curr_tok) {
case MUL:
left *= prim();
break;
case DIV:
left /= prim();
break;
default:
return left;
}
}
}
double prim() {
get_token();
switch (curr_tok) {
case NUMBER:
double v = number_value;
get_token();
return v;
case MINUS:
return -prim();
case LP:
double e = expr();
if (curr_tok != TOKEN.RP)
return error(")expected");
return e;
case FUNCTION:
String f = function_name;
get_token();
if (curr_tok != TOKEN.LP)
return error("( expected");
double z = prim();
if (curr_tok != TOKEN.RP)
return error(") expected");
if ("sin".equals(f)) {
return Math.sin(z);
} else {
return error("unknown function");
}
default:
return error("primary expression expected");
}
}
double error(String msg) {
error_msg = msg;
return Double.NaN;
}
TOKEN curr_tok;
double number_value;
String function_name;
String error_msg;
String input;
int pos;
void get_token() {
if (pos >= input.length()) {
curr_tok = TOKEN.END;
return;
}
char x = input.charAt(pos++);
switch (x) {
case '+':
curr_tok = TOKEN.PLUS;
break;
case '-':
curr_tok = TOKEN.MINUS;
break;
case '*':
curr_tok = TOKEN.MUL;
break;
case '/':
curr_tok = TOKEN.DIV;
break;
case '(':
curr_tok = TOKEN.LP;
break;
case ')':
curr_tok = TOKEN.RP;
break;
default:
if (Character.isDigit(x) || x == '.') {
curr_tok = TOKEN.NUMBER;
String s = "" + x;
while (pos < input.length() && (Character.isDigit(input.charAt(pos)) || input.charAt(pos) == '.')) {
s += input.charAt(pos);
++pos;
}
number_value = Double.parseDouble(s);
} else if (Character.isLetter(x)) {
curr_tok = TOKEN.FUNCTION;
String s = "" + x;
while (pos < input.length() && Character.isLetter(input.charAt(pos))) {
s += input.charAt(pos);
++pos;
}
function_name = s;
}
}
}
public static void main(String[] args) {
Calc2 calc = new Calc2();
calc.input = "sin(1)";
calc.pos = 0;
double res = calc.expr();
if (Double.isNaN(res)) {
System.out.println(calc.error_msg);
} else {
System.out.println(res);
}
}
}