Implement Simple Calculator program in java

What is Simple calculator?

It’s a straightforward program that will perform basic arithmetic effortlessly. There are four operations that will be performed by our calculator.

  • Addition
  • Subtract,
  • Multiply
  • Divide.

We will input the numbers and pick an operation to be performed.  We will perform the desired operation and display the output.

What is approach to implement Simple calculator?

  • Obtain two numbers and choose an operation (+,-,*,/).
  • Perform the selected arithmetic operation on the numbers.
  • Display the calculated result.
  • Optionally handle errors like division by zero or invalid input.
  • Optionally allow for multiple calculations without restarting.

Write a program to develop simple calculator in java

import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double num1, num2, result;
        char operator;

        System.out.println("Welcome to Simple Calculator!");
        System.out.print("Enter first number: ");
        num1 = scanner.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        operator = scanner.next().charAt(0);

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

        switch (operator) {
            case '+':
                result = num1 + num2;
                System.out.println("Result: " + result);
                break;
            case '-':
                result = num1 - num2;
                System.out.println("Result: " + result);
                break;
            case '*':
                result = num1 * num2;
                System.out.println("Result: " + result);
                break;
            case '/':
                if (num2 != 0) {
                    result = num1 / num2;
                    System.out.println("Result: " + result);
                } else {
                    System.out.println("Error! Division by zero is not allowed.");
                }
                break;
            default:
                System.out.println("Invalid operator entered.");
        }

        scanner.close();
    }
}

Output: Simple calculator Java

Welcome to Simple Calculator!
Enter first number: 20
Enter operator (+, -, *, /): *
Enter second number: 3
Result: 60.0

Welcome to Simple Calculator!
Enter first number: 10
Enter operator (+, -, *, /): +
Enter second number: 5
Result: 15.0

Scroll to Top