Java Calculator Tutorial with code explained

In this tutorial, we will build a simple calculator in Java that can perform basic arithmetic operations such as addition, subtraction, multiplication, division, and modulus.

We will use the command-line interface to interact with the user, allowing them to input numbers and choose an operation.

Features of the Calculator:

The user will input two numbers.
The user will choose the operation (add, subtract, multiply, divide, modulus).
The calculator will perform the operation and display the result.
The user will be able to perform multiple operations in a loop until they decide to exit.

Code for the Calculator

import java.util.Scanner;

public class Calculator {

    // Method to display the menu
    public static void displayMenu() {
        System.out.println("---- Calculator Menu ----");
        System.out.println("1. Add");
        System.out.println("2. Subtract");
        System.out.println("3. Multiply");
        System.out.println("4. Divide");
        System.out.println("5. Modulus");
        System.out.println("6. Exit");
        System.out.print("Choose an operation: ");
    }

    // Method to perform the calculation
    public static void calculate(double num1, double num2, int operation) {
        switch (operation) {
            case 1:
                System.out.println("Result: " + (num1 + num2));
                break;
            case 2:
                System.out.println("Result: " + (num1 - num2));
                break;
            case 3:
                System.out.println("Result: " + (num1 * num2));
                break;
            case 4:
                if (num2 != 0) {
                    System.out.println("Result: " + (num1 / num2));
                } else {
                    System.out.println("Error: Division by zero is undefined.");
                }
                break;
            case 5:
                if (num2 != 0) {
                    System.out.println("Result: " + (num1 % num2));
                } else {
                    System.out.println("Error: Modulus by zero is undefined.");
                }
                break;
            default:
                System.out.println("Invalid operation.");
                break;
        }
    }

    // Main method
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Main program loop
        while (true) {
            displayMenu(); // Display menu
            int operation = scanner.nextInt(); // Read operation from user

            // If user chooses to exit, break the loop
            if (operation == 6) {
                System.out.println("Exiting calculator. Goodbye!");
                break;
            }

            // Get numbers from user
            System.out.print("Enter the first number: ");
            double num1 = scanner.nextDouble();

            System.out.print("Enter the second number: ");
            double num2 = scanner.nextDouble();

            // Perform the calculation based on the user's choice
            calculate(num1, num2, operation);
            System.out.println(); // Print a blank line for readability
        }

        scanner.close(); // Close the scanner
    }
}

Explanation of the Code:

1. Main Method

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Main program loop
    while (true) {
        displayMenu(); // Display menu
        int operation = scanner.nextInt(); // Read operation from user

        // If user chooses to exit, break the loop
        if (operation == 6) {
            System.out.println("Exiting calculator. Goodbye!");
            break;
        }

        // Get numbers from user
        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();

        // Perform the calculation based on the user's choice
        calculate(num1, num2, operation);
        System.out.println(); // Print a blank line for readability
    }

    scanner.close(); // Close the scanner
}

Scanner Object: We create a Scanner object to take input from the user.
Main Program Loop: The program runs in an infinite loop (while(true)) to continuously prompt the user for inputs and operations. The loop continues until the user selects the “Exit” option (6).
Menu Display: The displayMenu() method is called to show the user the available options for arithmetic operations.
Operation Input: The user selects an operation by entering a number (1 to 6).
Number Input: The user inputs two numbers (num1 and num2) which will be used for the chosen operation.
Exiting the Program: If the user selects 6 (Exit), the program exits the loop and closes the scanner.

2. Menu Display

public static void displayMenu() {
    System.out.println("---- Calculator Menu ----");
    System.out.println("1. Add");
    System.out.println("2. Subtract");
    System.out.println("3. Multiply");
    System.out.println("4. Divide");
    System.out.println("5. Modulus");
    System.out.println("6. Exit");
    System.out.print("Choose an operation: ");
}

Menu Options: This method displays the available operations (Addition, Subtraction, Multiplication, Division, Modulus) and an option to exit.
Operation Input Prompt: The user is prompted to choose an operation by entering a number (1 to 6).

3. Calculate Method

public static void calculate(double num1, double num2, int operation) {
    switch (operation) {
        case 1:
            System.out.println("Result: " + (num1 + num2));
            break;
        case 2:
            System.out.println("Result: " + (num1 - num2));
            break;
        case 3:
            System.out.println("Result: " + (num1 * num2));
            break;
        case 4:
            if (num2 != 0) {
                System.out.println("Result: " + (num1 / num2));
            } else {
                System.out.println("Error: Division by zero is undefined.");
            }
            break;
        case 5:
            if (num2 != 0) {
                System.out.println("Result: " + (num1 % num2));
            } else {
                System.out.println("Error: Modulus by zero is undefined.");
            }
            break;
        default:
            System.out.println("Invalid operation.");
            break;
    }
}

Switch Statement: This method uses a switch statement to handle the various operations based on the user's input (operation):
Addition: Adds num1 and num2 and prints the result.
Subtraction: Subtracts num2 from num1 and prints the result.
Multiplication: Multiplies num1 by num2 and prints the result.
Division: Divides num1 by num2 if num2 is not zero. If num2 is zero, an error message is displayed since division by zero is undefined.
Modulus: Computes the modulus (remainder) of num1 divided by num2 if num2 is not zero. If num2 is zero, an error message is displayed.
Error Handling: For division and modulus, we check whether the second number (num2) is zero to prevent runtime errors.

Example Run of the Program

---- Calculator Menu ----
1. Add
2. Subtract
3. Multiply
4. Divide
5. Modulus
6. Exit
Choose an operation:
1

Enter the first number:
10

Enter the second number:
5

Result: 15.0

---- Calculator Menu ----
1. Add
2. Subtract
3. Multiply
4. Divide
5. Modulus
6. Exit
Choose an operation:
2

Enter the first number:
12

Enter the second number:
4

Result: 8.0

---- Calculator Menu ----
1. Add
2. Subtract
3. Multiply
4. Divide
5. Modulus
6. Exit
Choose an operation:
6

Exiting calculator. Goodbye!

Customizing the Calculator

You can extend or modify this basic calculator by adding more features, such as:

Exponentiation (power).
Square root calculation.
Scientific functions like sine, cosine, and tangent.
Support for multiple inputs and more complex expressions.

Conclusion

This basic Java calculator program demonstrates how to use fundamental Java concepts like loops, conditionals, methods, and input handling.

The program structure allows the user to continuously perform calculations until they choose to exit, making it interactive and easy to extend with additional features.

By following this tutorial, you have built a simple calculator that can perform basic arithmetic operations and handle division by zero errors.

You can further expand it to include more advanced operations or a graphical user interface (GUI) using Java Swing for a more advanced calculator experience.

Related posts

Java Random Maze Generator Using Swing Tutorial

Java Dice Roll Simulator Using Swing Tutorial

Java Palindrome Checker Using Swing Tutorial