forked from Rodlemus03/HT4-2.0
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculadora.java
More file actions
56 lines (49 loc) · 1.48 KB
/
Copy pathcalculadora.java
File metadata and controls
56 lines (49 loc) · 1.48 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
import java.util.Stack;
public class calculadora {
private static int operar(int a, int b, String operador) {
switch (operador) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
default:
throw new IllegalArgumentException("Operador ilegal: " + operador);
}
}
public static int evaluar(String expresion) {
Stack<Integer> stack = new Stack<>();
String[] digitos = expresion.split(" ");
for (String digito : digitos) {
if (isOperator(digito)) {
int b = stack.pop();
int a = stack.pop();
stack.push(operar(a, b, digito));
} else {
stack.push(Integer.parseInt(digito));
}
}
return stack.pop();
}
private static boolean isOperator(String token) {
boolean bandera=false;
if(token.equals("+")){
bandera=true;
}else if(token.equals("-")){
bandera=true;
}else if(token.equals("*")){
bandera=true;
}else if(token.equals("/")){
bandera=true;
}
return bandera;
}
public static void main(String[] args) {
String postfix = "3 5 + 2 *";
int result = evaluar(postfix);
System.out.println(postfix + " = " + result);
}
}