Java Code Example: simple calculator

The simple calculator expects user input for the arithmetic operation, and for the two numbers that are to be calculated together. Depending on the arithmetic symbol, a switch statement is used to decide which arithmetic operation is to be performed.

import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double firstNumber, secondNumber, result = 0.0;
        char arithmeticOperation;
    
        System.out.print("Please enter an arithmetic operation (+, -, *, /): ");
        arithmeticOperation = scan.next().charAt(0);
        System.out.print("Please enter your first number: ");
        firstNumber = scan.nextInt();
        System.out.print("Please enter your second number: ");
        secondNumber = scan.nextInt();
    
        switch (arithmeticOperation) {
            case '+' :
                result = firstNumber + secondNumber; 
                break;
            case '-' :
                result = firstNumber - secondNumber;
                break;
            case '*' : 
                result = firstNumber * secondNumber;
                break;
            case '/' :
                result = firstNumber / secondNumber;
                break;
            default:
                System.out.print("Unknown arithmetic symbol");
        }

        System.out.print(firstNumber + " " + arithmeticOperation + " " + secondNumber + " = " + result);
    }
}
Output
Please enter an arithmetic operation (+, -, *, /): -
Please enter your first number: 34
Please enter your second number: 23
34.0 - 23.0 = 11.0