-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartCalculator.java
More file actions
253 lines (240 loc) · 10.1 KB
/
Copy pathSmartCalculator.java
File metadata and controls
253 lines (240 loc) · 10.1 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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package calculator;
import java.math.BigDecimal;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
private static final Scanner scanner = new Scanner(System.in);
private static final HashMap<String, String> varDict = new HashMap<>();
private static final Deque<String> symStack = new ArrayDeque<>();
private static final Deque<String> numStack = new ArrayDeque<>();
public static void main(String[] args) {
// put your code here
boolean foward = true;
while (foward) {
String userInput = scanner.nextLine();
if ("".equals(userInput)) {
continue;
}
if ('/' == userInput.charAt(0)) {
switch (userInput) {
case "/exit":
System.out.println("Bye!");
foward = false;
break;
case "/help":
System.out.println("The program support parenthesis now! But still strict with spaces...");
break;
default:
System.out.println("Unknown command");
break;
}
} else {
String mode = switchMode(userInput);
switch (mode) {
case "var":
storeVariable(userInput);
break;
case "cal":
userInput = userInput.replaceAll("\\("," ( ");
userInput = userInput.replaceAll("\\)", " ) ");
String result = calculate(reversePolishNotation(parseInput(userInput)));
System.out.println(result);
break;
}
}
}
}
private static String switchMode(String userInput) {
if (userInput.matches("^[^=]+=[^=]+$")) {
return "var";
} else if (userInput.matches(".*=.*")) {
System.out.println("Invalid assignment");
return "err";
} else {
return "cal";
}
}
private static void storeVariable(String userInput) {
String[] nameWithVal = userInput.split("\\s*=\\s*");
if (nameWithVal[0].matches("[A-Za-z]+")) {
if (nameWithVal.length == 2 && nameWithVal[1].matches("(-?[0-9][0-9]*)|([A-Za-z]+)")) {
if (nameWithVal[1].matches("[A-Za-z]+") && varDict.containsKey(nameWithVal[1])) {
varDict.put(nameWithVal[0], varDict.get(nameWithVal[1]));
} else if (nameWithVal[1].matches("-?[0-9][0-9]*")) {
varDict.put(nameWithVal[0], nameWithVal[1]);
} else {
System.out.println("Unknown variable");
}
} else {
System.out.println("Invalid assignment");
}
} else {
System.out.println("Invalid identifier");
}
}
private static String reversePolishNotation(String userInput) {
if ("Invalid expression".equals(userInput)) {
return "Invalid expression";
}
String[] strings = userInput.replaceAll("\\s+", " ").split(" ");
StringBuilder sb = new StringBuilder();
for (String s : strings) {
if (s.matches("(-?([1-9][0-9]*)|([a-zA-Z]*))")) {
sb.append(s).append(" ");
} else {
switch (s) {
case "(":
symStack.offerFirst(s);
break;
case ")":
while (!"(".equals(symStack.peekFirst())) {
sb.append(symStack.pollFirst()).append(" ");
}
symStack.pollFirst();
break;
case "+":
case "-":
while (!symStack.isEmpty()) {
String symbol = symStack.peekFirst();
if ("(".equals(symbol)) {
break;
} else {
sb.append(symStack.pollFirst()).append(" ");
}
}
symStack.offerFirst(s);
break;
case "*":
case "/":
while (!symStack.isEmpty()) {
String symbol = symStack.peekFirst();
if ("*".equals(symbol) || "/".equals(symbol) || "^".equals(symbol)) {
sb.append(symStack.pollFirst()).append(" ");
} else {
break;
}
}
symStack.offerFirst(s);
break;
case "^":
while (!symStack.isEmpty()) {
String symbol = symStack.peekFirst();
if ("^".equals(symbol)) {
sb.append(symStack.pollFirst()).append(" ");
} else {
break;
}
}
symStack.offerFirst(s);
break;
}
}
}
while (!symStack.isEmpty()) {
sb.append(symStack.pollFirst()).append(" ");
}
return sb.toString();
}
private static void refreshStack() {
symStack.clear();
numStack.clear();
}
private static boolean symbolCheck(String userInput) {
Pattern validPattern = Pattern.compile("(\\s*[0-9a-zA-Z\\+\\-\\*\\/\\^\\(\\)]\\s*)*[0-9a-zA-Z\\)]\\s*$");
Matcher validMatcher = validPattern.matcher(userInput);
if (validMatcher.matches() && !userInput.matches(".*(\\s*[\\*\\/\\^]\\s*){2,}.*")) {
return !userInput.matches(".*\\([^)]*") && !userInput.matches("[^(]*\\).*");
}
return false;
}
private static String parseInput(String userInput) {
if (userInput.matches("^[a-zA-Z]+$")) {
return userInput;
}
if (symbolCheck(userInput)) {
Pattern pattern = Pattern.compile("(\\+-)|(-\\+)|(--)|(\\+\\+)");
Matcher matcher = pattern.matcher(userInput);
while (matcher.find()) {
userInput = userInput.replaceAll("(\\++)|(--)", "+");
userInput = userInput.replaceAll("(\\+-)|(-\\+)", "-");
matcher = pattern.matcher(userInput);
}
} else {
userInput = "Invalid expression";
}
return userInput;
}
private static String parseNum(String num) {
return num.matches("-?[1-9][0-9]*") ? num : varDict.containsKey(num) ?
String.valueOf(varDict.get(num)) : "Unknown variable";
}
private static String calculate(String userInput) {
if ("Invalid expression".equals(userInput)) {
return userInput;
}
refreshStack();
String[] splitUserInput = userInput.split(" ");
for (String s : splitUserInput) {
if (s.matches("-?[1-9][0-9]*")) {
numStack.offerFirst(s);
} else if (s.matches("^[a-zA-Z]+$")) {
numStack.offerFirst(parseNum(s));
} else {
if (!numStack.isEmpty()) {
String b = parseNum(numStack.pollFirst());
String a = parseNum(numStack.pollFirst());
if ("Unknown variable".equals(a) || "Unknown variable".equals(b)) {
return "Unknown variable";
}
if (a.length() > 8 || b.length() > 8) {
BigDecimal numA = new BigDecimal(a);
BigDecimal numB = new BigDecimal(b);
switch (s) {
case "+":
numStack.offerFirst(numA.add(numB).toPlainString());
break;
case "-":
numStack.offerFirst(numA.subtract(numB).toPlainString());
break;
case "*":
numStack.offerFirst(numA.multiply(numB).toPlainString());
break;
case "/":
numStack.offerFirst(numA.divide(numB).toPlainString());
break;
default:
return "Big numbers only support + - * /";
}
} else {
switch (s) {
case "+":
numStack.offerFirst(String.valueOf(Long.parseLong(a)+ Long.parseLong(b)));
break;
case "-":
numStack.offerFirst(String.valueOf(Long.parseLong(a) - Long.parseLong(b)));
break;
case "*":
numStack.offerFirst(String.valueOf(Long.parseLong(a) * Long.parseLong(b)));
break;
case "/":
numStack.offerFirst(String.valueOf(Long.parseLong(a) / Long.parseLong(b)));
break;
case "^":
numStack.offerFirst(String.valueOf(Math.round(Math.pow(Double.parseDouble(a), Double.parseDouble(b)))));
break;
}
}
}
}
}
if (symStack.isEmpty()) {
return numStack.peekFirst();
} else {
return "Invalid expression";
}
}
}