-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathCalculator.java
More file actions
43 lines (37 loc) · 1.35 KB
/
Calculator.java
File metadata and controls
43 lines (37 loc) · 1.35 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
package calculation;
import validation.Validator;
import java.util.*;
public class Calculator {
private final String expression;
public Calculator(String infixExpr) {
Converter converter = new PostfixConverter(infixExpr);
expression = converter.convert();
}
public int calculate() {
Stack<Integer> calculationStack = new Stack<>();
String[] exprArray = expression.split("");
for (String item : exprArray) {
if (Validator.isNumber(item)) {
calculationStack.push(Integer.parseInt(item));
} else if (Validator.isOperator(item)) {
Integer operand2 = calculationStack.pop();
Integer operand1 = calculationStack.pop();
switch (item) {
case "+":
calculationStack.push(operand1 + operand2);
break;
case "-":
calculationStack.push(operand1 - operand2);
break;
case "*":
calculationStack.push(operand1 * operand2);
break;
case "/":
calculationStack.push(operand1 / operand2);
break;
}
}
}
return calculationStack.pop();
}
}