fin piles
This commit is contained in:
56
DEV3.2/Piles/chaine/Arithmetique.java
Normal file
56
DEV3.2/Piles/chaine/Arithmetique.java
Normal file
@@ -0,0 +1,56 @@
|
||||
public class Arithmetique {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length == 0) {
|
||||
System.out.println("Veuillez fournir une expression en notation polonaise inversée.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Utilisation de notre implémentation PileChainee pour la pile
|
||||
Pile<Integer> stack = new PileChainee<>();
|
||||
|
||||
try {
|
||||
for (String token : args) {
|
||||
switch (token) {
|
||||
case "+":
|
||||
// Addition
|
||||
stack.push(stack.pop() + stack.pop());
|
||||
break;
|
||||
case "-":
|
||||
// Soustraction (attention à l'ordre)
|
||||
int b = stack.pop();
|
||||
int a = stack.pop();
|
||||
stack.push(a - b);
|
||||
break;
|
||||
case "x":
|
||||
// Multiplication
|
||||
stack.push(stack.pop() * stack.pop());
|
||||
break;
|
||||
case "/":
|
||||
// Division (attention à l'ordre)
|
||||
b = stack.pop();
|
||||
a = stack.pop();
|
||||
if (b == 0) {
|
||||
throw new ArithmeticException("Division par zéro");
|
||||
}
|
||||
stack.push(a / b);
|
||||
break;
|
||||
default:
|
||||
// Si ce n'est pas un opérateur, alors c'est un nombre
|
||||
stack.push(Integer.parseInt(token));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Le résultat final doit être le seul élément restant sur la pile
|
||||
if (stack.size() == 1) {
|
||||
System.out.println("= " + stack.pop());
|
||||
} else {
|
||||
System.out.println("Erreur : Expression incorrecte.");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Erreur lors de l'évaluation de l'expression : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user