C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Simple calculator using user input - Java Program

import java.util.Scanner;

 

public class SimpleCalculator {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        // Taking two numbers from the user

        System.out.print("Enter first number: ");

        double num1 = sc.nextDouble();

 

        System.out.print("Enter second number: ");

        double num2 = sc.nextDouble();

 

        // Showing operation menu

        System.out.println("\nChoose an operation:");

        System.out.println("1. Addition (+)");

        System.out.println("2. Subtraction (-)");

        System.out.println("3. Multiplication (*)");

        System.out.println("4. Division (/)");

 

        System.out.print("Enter your choice (1-4): ");

        int choice = sc.nextInt();

 

        double result = 0;

 

        // Performing operation based on user's choice

        switch (choice) {

            case 1:

                result = num1 + num2;

                break;

 

            case 2:

                result = num1 - num2;

                break;

 

            case 3:

                result = num1 * num2;

                break;

 

            case 4:

                if (num2 != 0) {

                    result = num1 / num2;

                } else {

                    System.out.println("Error: Division by zero is not allowed!");

                    sc.close();

                    return;

                }

                break;

 

            default:

                System.out.println("Invalid choice! Please select between 1-4.");

                sc.close();

                return;

        }

 

        // Displaying the result

        System.out.println("\nResult: " + result);

 

        sc.close();

    }

}

Output

 
OUTPUT 1:
Enter first number: 12
Enter second number: 4

Choose an operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter your choice (1-4): 3

Result: 48.0

Explanation

1. Input from user

The program asks for:

  • First number
  • Second number
  • User’s choice of operation (1–4)

Scanner is used to capture input.

2. Menu for Operations

User selects which operation to perform:

  • 1 → Addition
  • 2 → Subtraction
  • 3 → Multiplication
  • 4 → Division

3. Switch–Case Logic

Based on choice, the program performs the matching operation:

switch (choice) {

    case 1: result = num1 + num2; break;

    case 2: result = num1 - num2; break;

    case 3: result = num1 * num2; break;

    case 4: result = num1 / num2; break;

}

4. Division by Zero Handling

Before dividing, the program checks:

if (num2 != 0)

If zero, it shows an error and stops.

5. Display Output

The result of the chosen operation is printed.