Site icon

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.

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?

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

Exit mobile version