Make a Simple Calculator in Java

Exercise:

Write a Java Program to make a simple calculator using switch statement.

Click Here to View the Solution!
import java.util.Scanner;
 
public class Calculator {
 
  public static void main(String[] args) {
 
    Scanner reader = new Scanner(System.in);
    System.out.print("Enter two numbers: ");
    // nextDouble() reads next double from the keyboard and store them as double 
    double firstNum = reader.nextDouble();
    double secondNum = reader.nextDouble();
 
    System.out.print("Enter an operator (+, -, *, /): ");
    char operator = reader.next().charAt(0);
 
    double result;
 
    switch (operator) {
      case '+':
        result = firstNum + secondNum;
        break;
 
      case '-':
        result = firstNum - secondNum;
        break;
 
      case '*':
        result = firstNum * secondNum;
        break;
 
      case '/':
        result = firstNum / secondNum;
        break;
 
      // If statement to check operator doesn't match any case constant(+, -, *, /)
      default:
        System.out.printf("Error! Please choose a valid operator");
        return;
    }
 
    System.out.println(firstNum + " " + operator + " " + secondNum + " = " + result);
  }
} 
Click Here to View the Output!
Enter two numbers: 4
 7
 Enter an operator (+, -, *, /): *
 4.0 * 7.0 = 28.0
Click Here to View the Explanation!
  • This program is used to create a simple calculator by using a switch…case method in Java.
  • The calculator will be able to calculate simple mathematical operations, addition, subtraction, multiplication and division between two values.
  • Initially, the program will request the user to enter two numbers. These two numbers ‘4’ and ‘7’ will be stored in two different variables ‘firstNum’ and ‘secondNum’ through the nextDouble() method of the scanner object.
  • Then the program will request the user to select one of the operators from the displayed options, ‘+, -,*,/’ which are stated in the program in 4 separate cases. This operator will be stored in the variable ‘operator’ through the next() method of the scanner object.
  • After the user enters the character ‘*’, the control shifts to the case ‘*’ where the operation ‘result = firstNum * secondNum’ exists.
  • This operation will calculate the product of the two number firstNum and secondNum and store their output in the variable result. After the operation is carried out, the break statement will end the switch statement.
  • An exception is included in the program at the end of the switch statement that if the user enters any character except for the operator characters mentioned in the cases, then display the error message using printf().
  • Lastly, the operation statement will be displayed with the result.

%d bloggers like this: