Simple Calculator Program in Java

In this source code example, we will learn how to create a simple calculator using Core Java.

Simple Calculator Program in Java

Here is an example of a simple calculator program written in Java:
import java.util.Scanner;

public class Calculator {

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

        System.out.println("Enter first number:");
        double num1 = scanner.nextDouble();

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

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

        double result;

        switch (operator) {
            case '+':
                result = num1 + num2;
                System.out.println(num1 + " + " + num2 + " = " + result);
                break;

            case '-':
                result = num1 - num2;
                System.out.println(num1 + " - " + num2 + " = " + result);
                break;

            case '*':
                result = num1 * num2;
                System.out.println(num1 + " * " + num2 + " = " + result);
                break;

            case '/':
                result = num1 / num2;
                System.out.println(num1 + " / " + num2 + " = " + result);
                break;

            default:
                System.out.println("Invalid operator!");
                break;
        }
    }
}

Output:

javac Calculator.java
java Calculator
This program uses the Scanner class to get input from the user, and a switch statement to perform the appropriate calculation based on the operator entered by the user. The program takes two numbers as input and one operator. Then it performs the operation and prints the result.

You can run this program by compiling it with the javac command and then run the resulting class file with the java command.

Comments