APL/DEV 3.2/TP04/Arithmetique/Arithmetique.java

49 lines
1.3 KiB
Java
Raw Normal View History

2022-10-26 11:13:11 +02:00
import java.util.ArrayDeque;
/**
* Arithmetique
*/
public class Arithmetique {
public static void main(String[] args) {
ArrayDeque<Integer> pile = new ArrayDeque<>();
for (String arg : args) {
try {
int n = Integer.parseInt(arg);
pile.addFirst(n);
} catch (NumberFormatException e) {
if (pile.size() < 2) {
System.err.println("Invalid stack size.");
return;
}
int n2 = pile.pollFirst();
int n1 = pile.pollFirst();
switch (arg) {
case "+":
pile.addFirst(n1 + n2);
break;
case "-":
pile.addFirst(n1 - n2);
break;
case "/":
pile.addFirst(n1 / n2);
break;
case "x":
pile.addFirst(n1 * n2);
break;
default:
System.err.println("Invalid operator");
return;
}
}
}
System.out.println(pile.pollFirst());
}
}