forked from BrygoQQ/calc_groovy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.groovy
112 lines (90 loc) · 3.24 KB
/
calc.groovy
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import org.apache.tools.ant.filters.TokenFilter
import static java.lang.System.*;
class Calc {
static List<String> check_for_brek(List<String> result){
String tmp_str = ""
for(int i = 0; i < result.size(); i++) {
if (result[i] == "(") {
int j = i
i++
while (result[i] != ')') {
tmp_str += (result[i])
result.remove(i)
}
result.remove(i)
tmp_str = calculator(tmp_str)
tmp_str = tmp_str.replace("[", "")
tmp_str = tmp_str.replace("]", "")
result.set(j, tmp_str)
}
}
return result
}
static List<String> check_for_mult(List<String> result){
for(int i = 0; i < result.size(); i++) {
if (result[i] == '*') {
result.set(i - 1, Double.toString(Double.parseDouble(result[i - 1]) * Double.parseDouble(result[i + 1])))
result.remove(i + 1)
result.remove(i)
i = 0;
}
}
return result
}
static List<String> check_for_div(List<String> result){
for(int i = 0; i < result.size(); i++) {
if (result[i] == '/') {
if ( result[i+1] != '0') {
result.set(i - 1, (Double.toString((Double.parseDouble(result[i - 1]) / (Double.parseDouble(result[i + 1]))))))
result.remove(i + 1)
result.remove(i)
i = 0
} else {
result.set(0, "infinity")
}
}
}
return result
}
static List<String> check_for_sum(List<String> result){
for(int i = 0; i < result.size(); i++) {
if (result[i] == '+') {
result.set(i - 1, (Double.toString((Double.parseDouble(result[i - 1])) + (Double.parseDouble(result[i + 1])))))
result.remove(i + 1)
result.remove(i)
i = 0
}
}
return result
}
static List<String> check_for_sub(List<String> result){
for(int i = 0; i < result.size(); i++) {
if (result[i] == '-') {
result.set(i - 1, (Double.toString((Double.parseDouble(result[i - 1])) - (Double.parseDouble(result[i + 1])))))
result.remove(i + 1)
result.remove(i)
i = 0
}
}
return result
}
static String calculator(String x){
List<String> result = new ArrayList<String>(Arrays.asList(x.split("(?<=[-+*/()])|(?=[-+*/()])")));
System.out.println(result);
check_for_brek(result);
check_for_mult(result);
check_for_div(result);
check_for_sum(result);
check_for_sub(result);
return result
}
}
String hello="Hello,this is calculator!";
println hello
def a = {int z = 2,int w = 2 ->
println "${z} plus ${w} is ?"
}
println "Enter your expression"
Scanner sc = new Scanner(System.in);
String expr = sc.nextLine();
println Calc.calculator(expr)