-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ3.java
83 lines (73 loc) · 3.09 KB
/
Q3.java
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package test;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.lang.Character;
import java.lang.Integer;
public class Q3{
public static double calc(String expression) {
Stack<String>calcStack=new Stack<>();
Stack<Expression>checkingExp=new Stack<>();
Queue<String>queue=new LinkedList<>();
String[] out=expression.split("(?<=[-+*/()])|(?=[-+*/()])");
for(String str:out){
if(isDoublenum(str))
queue.add(str);
else{
switch (str){
case "/":
case "*":
case "(":
calcStack.push(str);
break;
case "+":
case "-":
while(!calcStack.isEmpty()&&(!calcStack.peek().equals("("))){
queue.add(calcStack.pop());
}
calcStack.push(str);
break;
case ")":
while(!calcStack.peek().equals("(")){
queue.add(calcStack.pop());
}
calcStack.pop();
break;
}
}
}
while(!calcStack.isEmpty())
queue.add(calcStack.pop());
for(String str:queue) {
if (isDoublenum(str))
checkingExp.push(new Number(Double.parseDouble(str)));
else {
Expression right = checkingExp.pop();
Expression left = checkingExp.pop();
switch (str) {
case "/":
checkingExp.push(new Div(left, right));
break;
case "*":
checkingExp.push(new Mul(left, right));
break;
case "+":
checkingExp.push(new Plus(left, right));
break;
case "-":
checkingExp.push(new Minus(left, right));
}
}
}
double result=Math.floor(checkingExp.peek().calculate());
return Math.floor((checkingExp.peek().calculate()*1000))/1000;
}
private static boolean isDoublenum(String x){
try {
Double.parseDouble(x);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}