-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpression.java
More file actions
51 lines (41 loc) · 955 Bytes
/
Expression.java
File metadata and controls
51 lines (41 loc) · 955 Bytes
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
package stack;
public class Expression {
public static double eval(String exp) {
Stack<Double> aux = new LinkedStack<>();
for (String e : exp.split(" ")) {
if ("+-/*^".contains(e))
aux.push(evalCalc(aux.pop(), aux.pop(), e));
else
aux.push(Double.parseDouble(e));
}
return aux.pop();
}
public static boolean isProperlyParenthesized(String exp) {
Stack<Character> aux = new LinkedStack<>();
for (int i = 0; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '(') {
aux.push(c);
} else if (c == ')') {
if (aux.isEmpty())
return false;
aux.pop();
}
}
return aux.isEmpty();
}
private static double evalCalc(double valor2, double valor1, String op) {
switch (op) {
case "+":
return valor1 + valor2;
case "-":
return valor1 - valor2;
case "/":
return valor1 / valor2;
case "^":
return Math.pow(valor1, valor2);
default:
return valor1 * valor2;
}
}
}