-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathCalculation.java
More file actions
59 lines (49 loc) · 1.84 KB
/
Calculation.java
File metadata and controls
59 lines (49 loc) · 1.84 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
package co.programmers.domain;
import java.util.ArrayList;
import java.util.List;
public class Calculation {
private List<String> parsedExpression;
private List<String> operators;
private Expression expression;
public Calculation(Expression expression) {
this.expression = expression;
parsedExpression = new ArrayList<>();
operators = new ArrayList<>();
}
public Double calculate() throws ArithmeticException {
parsedExpression = expression.split();
operators = extractOperators();
Operator.decideCalculationOrder(operators);
for (String operator : operators) {
int operatorPosition = parsedExpression.indexOf(operator);
Double[] operands = extractOperands(operator);
Double calculationRes = Operator.calculate(operator, operands[0], operands[1]);
storeIntermediateResult(operatorPosition, calculationRes);
removeCompletedExpression(operatorPosition, operands.length);
}
return calcFinalResult();
}
private void removeCompletedExpression(int operatorPosition, int count) {
for (int cnt = 0; cnt <= count; cnt++) {
parsedExpression.remove(operatorPosition);
}
}
private void storeIntermediateResult(int operatorPosition, Double calculationRes) {
parsedExpression.add(operatorPosition - 1, String.valueOf(calculationRes));
}
private Double[] extractOperands(String operator) {
int operatorIdx = parsedExpression.indexOf(operator);
Double operand1 = Double.parseDouble(parsedExpression.get(operatorIdx - 1));
Double operand2 = Double.parseDouble(parsedExpression.get(operatorIdx + 1));
return new Double[] {operand1, operand2};
}
private List<String> extractOperators() {
expression.eliminateWhiteSpace();
List<String> parsed = expression.split("\\d+");
parsed.removeIf(String::isEmpty);
return parsed;
}
private Double calcFinalResult() {
return Double.parseDouble(parsedExpression.get(0));
}
}