# Basic calculator program using Java

Java 8Object Oriented ProgrammingProgramming

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: ");
System.out.print("\nEnter an operator (+, -, *, /): ");
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("\nThe result is given as follows:\n");
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: ");
System.out.print("\nEnter 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("\nThe result is given as follows:\n");
System.out.printf(num1 + " " + op + " " + num2 + " = " + ans);
Published on 06-Dec-2018 06:34:14