English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Array

Java Programmation Orientée Objet (I)

Java Programmation Orientée Objet (II)

Java Programmation Orientée Objet (III)

Gestion des exceptions Java

Java List

Java Queue (File d'attente)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Autres sujets Java

Création d'une calculatrice simple en utilisant switch ... case dans un programme Java

Comprehensive Java Examples

Dans ce programme, vous apprendrez à créer une calculatrice simple en utilisant switch..case dans Java. Cette calculatrice pourra effectuer des opérations d'addition, de soustraction, de multiplication et de division sur deux nombres.

Exemple : calculatrice simple en utilisant switch-case

import java.util.Scanner;
public class Calculator {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.print("Entrez deux nombres: ");
        //nextDouble() lit le prochain double depuis le clavier
        double first = reader.nextDouble();
        double second = reader.nextDouble();
        +, -, *, /
        char operator = reader.next().charAt(0);
        double result;
        switch(operator)
        {
            case ''+':
                result = first + second;
                break;
            case ''-':
                result = first - second;
                break;
            case ''*':
                result = first * second;
                break;
            case ''/':
                result = first / second;
                break;
            // Opérateur non correspondant (+, -, *, /)
            default:
                System.out.printf("Erreur ! opérateur incorrect");
                return;
        }
        System.out.printf("%.1f %c %.2f1f = %.2f1f", first, operator, second, result);
    }
}

When running the program, the output is:

Enter two numbers 1.5
4.5
Enter an operator (+, -, *, /) : *
1.5 * 4.5 = 6.8

User input is*The operator is stored in the operator variable using the next() method of the Scanner object.

Similarly, use the nextDouble() method of the Scanner object to get two operands1.5and4.5are stored separately in the variables first and second.

because the operator*with the condition case '*'matches: therefore the program control jumps to

result = first * second;

The statement calculates the result and stores it in the variable result, and then break; ends the switch statement.

Finally, the printf statement is executed.

Note: We use the printf() method instead of println. This is because here we want to print a formatted string. For more information, please visitJava printf() method.

Comprehensive Java Examples