Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in
Sequence
Console calculator
Core exercise
A calculator that chains operations until the user chooses 0. Stick to the signatures below: the checks rely on them.
Goals: Menus, switch, loops, splitting into methods.
Features
- Menu: 1) Addition 2) Soustraction 3) Multiplication 4) Division 0) Quitter (keep these French labels, the checks look for them).
- Reading two numbers (
double) and printing the result. - A loop that chains operations until 0 (quit).
- Handling division by zero: an error message (containing “Erreur”), not a crash.
Steps
afficherMenu()→ prints the options.lireChoix(Scanner sc)→ returns an int between 0 and 4.lireOperande(Scanner sc, String nom)→ returns a double.- One method per operation:
addition(a, b),soustraction(a, b),multiplication(a, b),division(a, b). boucleCalculatrice(Scanner sc)→ orchestrates the whole thing with ado…while.
Criteria: No crash, error cases handled, code split into clear methods.
A workshop goes here: you write and run code in it. It requires JavaScript.
Starting code
Calculatrice.java
import java.util.Scanner;
public class Calculatrice {
public static void afficherMenu() {
// TODO : afficher les 5 options
}
public static int lireChoix(Scanner sc) {
// TODO : lire un entier entre 0 et 4
return 0;
}
public static double lireOperande(Scanner sc, String nom) {
// TODO : demander puis lire un double
return 0;
}
public static double addition(double a, double b) {
return 0;
}
public static double soustraction(double a, double b) {
return 0;
}
public static double multiplication(double a, double b) {
return 0;
}
public static double division(double a, double b) {
return 0;
}
public static void boucleCalculatrice(Scanner sc) {
// TODO : do { menu, choix, operandes, resultat } while (choix != 0);
}
}
Exercices.java
import java.util.Scanner;
public class Exercices {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Calculatrice.boucleCalculatrice(sc);
sc.close();
}
}
The core exercise is validated in the workshop, which requires JavaScript.
Hint 1
Division by zero on doubles does not throw an exception: it gives Infinity. It is up to you to test b == 0 before dividing.
Extensions
- History of calculations (via
ArrayList<String>). - Scientific mode: power, square root (check the domains).