-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathCalculator.java
More file actions
45 lines (36 loc) · 1.27 KB
/
Calculator.java
File metadata and controls
45 lines (36 loc) · 1.27 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
package com.serenitydojo.calculator;
import com.google.common.base.Splitter;
import java.util.List;
import static org.apache.commons.lang3.StringUtils.isNumeric;
public class Calculator {
public int evaluate(String expression) {
if (expression.isEmpty()) {
return 0;
}
List<String> tokens = Splitter.on(" ").splitToList(expression);
int runningTotal = 0;
String nextOperator = "+";
for(String token : tokens) {
if (!isNumeric(token)) {
nextOperator = token;
} else {
runningTotal = process(runningTotal, nextOperator, token);
}
}
return runningTotal;
}
private int process(int runningTotal, String nextOperator, String token) {
switch (nextOperator) {
case "+":
return runningTotal + Integer.parseInt(token);
case "-":
return runningTotal - Integer.parseInt(token);
case "*":
return runningTotal * Integer.parseInt(token);
case "/":
return runningTotal / Integer.parseInt(token);
default:
throw new IllegalMathsOperatorException("Unknown operator " + nextOperator);
}
}
}