How to Create a Calculator using Java

Calculator in Java- Here is a simple calculator program in Java that can perform basic arithmetic operations (addition, subtraction, multiplication, and division). The program prompts the user to enter two numbers and an operator, and then performs the operation on the numbers:

import java.util.Scanner;

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

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

    System.out.println("Enter the 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;
        break;
      case '-':
        result = num1 - num2;
        break;
      case '*':
        result = num1 * num2;
        break;
      case '/':
        result = num1 / num2;
        break;
      default:
        System.out.println("Invalid operator!");
        return;
    }

    System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
  }
}

To run this program, save it in a file called Calculator.java and then use the javac command to compile it:

javac Calculator.java

Then run the program using the java command:

java Calculator

The program will prompt you to enter two numbers and an operator, and then it will perform the operation and display the result.

Create a Calculator Using HTML, CSS, and JavaScript