Basic calculator program using Java


A basic calculator is able to add, subtract, multiply or divide two numbers. This is done using a switch case. A program that demonstrates this is given as follows −

Example

import java.util.Scanner;
public class Calculator {
   public static void main(String[] args) {
      double num1;
      double num2;
      double ans;
      char op;
      Scanner reader = new Scanner(System.in);
      System.out.print("Enter two numbers: ");
      num1 = reader.nextDouble();
      num2 = reader.nextDouble();
      System.out.print("
Enter an operator (+, -, *, /): ");       op = reader.next().charAt(0);       switch(op) {          case '+': ans = num1 + num2;             break;          case '-': ans = num1 - num2;             break;          case '*': ans = num1 * num2;             break;          case '/': ans = num1 / num2;             break;       default: System.out.printf("Error! Enter correct operator");          return;       }       System.out.print("
The result is given as follows:
");       System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);    } }

Output

Enter two numbers: 10.0 7.0
Enter an operator (+, -, *, /): -
The result is given as follows:
10.0 - 7.0 = 3.0

Now let us understand the above program.

The two numbers as well as the operator is acquired from the user. The code snippet that demonstrates this is given as follows −

double num1;
double num2;
double ans;
char op;
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
num1 = reader.nextDouble();
num2 = reader.nextDouble();
System.out.print("
Enter an operator (+, -, *, /): "); op = reader.next().charAt(0);

A switch case is used to perform the specified operation on the two numbers. If the operator entered is incorrect, an error message is displayed. The code snippet that demonstrates this is given as follows −

switch(op) {
   case '+': ans = num1 + num2;
      break;
   case '-': ans = num1 - num2;
      break;
   case '*': ans = num1 * num2;
      break;
   case '/': ans = num1 / num2;
      break;
default: System.out.printf("Error! Enter correct operator");
return;
}

Finally, the result is printed. The code snippet that demonstrates this is given as follows −

System.out.print("
The result is given as follows:
"); System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements