-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
46 lines (34 loc) · 1.18 KB
/
Calculator.java
File metadata and controls
46 lines (34 loc) · 1.18 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
package node;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Stack;
public class Calculator {
public static void main(String[] args) {
String temp = "1 - 3 + 4 + 5";
System.out.println(evaluate(temp));
List<String> list = new Stack<>();
}
public static int evaluate(final String input) {
//split string into element array
//put all element on stack , via looping for each
//while loop , stack.size()>1
String[] strings = input.split(" ");
Deque<String> stack = new ArrayDeque<>();
for (String ele: strings) {
stack.add(ele);
}
while(stack.size() > 1){
int left = Integer.parseInt(stack.pop());
String operator = stack.pop();
int right = Integer.parseInt(stack.pop());
int result = 0;
switch(operator){
case "+" : result = left+right;break;
case "-" : result = left-right; break;
}
stack.push(String.valueOf(result));
}
return Integer.parseInt(stack.pop());
}
}