-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathCalculate.java
More file actions
66 lines (58 loc) · 2.07 KB
/
Calculate.java
File metadata and controls
66 lines (58 loc) · 2.07 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
package org.example;
import java.util.Stack;
public class Calculate implements CalOrder{
private String expression;
Stack<String> expressionStack = new Stack<>();
ExpressionRepository repository = new ExpressionRepository();
int result = 0;
public Calculate(String expression) {
this.expression = expression;
String[] expressionArr = expression.split(" ");
for (String inputVal : expressionArr) {
expressionStack.add(inputVal);
}
}
public void calculate(){
calPriorityFirst();
calPrioritySecond();
}
@Override
public void calPriorityFirst() {
for (int i = 1; i < expressionStack.size(); i+=2) {
if (expressionStack.get(i).equals("*")) {
multiply(i);
i -= 2;
} else if (expressionStack.get(i).equals("/")) {
divide(i);
i -= 2;
}
}
}
@Override
public void calPrioritySecond() {
result = Integer.parseInt(expressionStack.get(0));
for (int i = 1; i < expressionStack.size(); i += 2) {
if (expressionStack.get(i).equals("+")) {
result += Integer.parseInt(expressionStack.get(i + 1));
} else {
result -= Integer.parseInt(expressionStack.get(i + 1));
}
}
System.out.println(result);
repository.save(expression,result);
}
public void multiply(int idx){
result = Integer.parseInt(expressionStack.get(idx - 1)) * Integer.parseInt(expressionStack.get(idx + 1));
expressionStack.add(idx - 1, String.valueOf(result));
expressionStack.remove(idx);
expressionStack.remove(idx);
expressionStack.remove(idx);
}
public void divide(int idx) {
result = Integer.parseInt(expressionStack.get(idx - 1)) / Integer.parseInt(expressionStack.get(idx + 1));
expressionStack.add(idx - 1, String.valueOf(result));
expressionStack.remove(idx);
expressionStack.remove(idx);
expressionStack.remove(idx);
}
}