Files
BUT2/TP_DEV3.2/Piles/Arithmetique.java
2025-10-23 14:28:03 +02:00

52 lines
1.5 KiB
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import java.util.Stack;
public class Arithmetique {
public static void main(String[] args) {
// Exemple : 18 6 1 2 + 9 + / + 8 7 - *
// String[] args = {"18", "6", "1", "2", "+", "9", "+", "/", "+", "8", "7", "-", "*"};
Stack<Integer> pile = new Stack<>();
for (String element : args) {
if (estNombre(element)) {
// Si cest un nombre, on le met dans la pile
pile.push(Integer.parseInt(element));
} else {
// Sinon cest un opérateur on dépile 2 valeurs
int b = pile.pop();
int a = pile.pop();
int resultat = calculer(a, b, element);
// On empile le résultat
pile.push(resultat);
}
}
// À la fin, il reste le résultat final dans la pile
System.out.println("Résultat = " + pile.pop());
}
// Vérifie si une chaîne est un nombre
public static boolean estNombre(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
// Calcule a (op) b
public static int calculer(int a, int b, String op) {
switch (op) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b;
default:
throw new IllegalArgumentException("Opérateur inconnu : " + op);
}
}
}