# Java Simple Calculator Program

17 Sep 2019 10:01 am || 0

In this tutorial, you will learn how to make a simple calculator program in java to perform basic mathematical operations like addition, subtraction, division, and multiplication according to the user input. The program will take two number as an input and then ask the user to enter the mathematical operation (+, -, * and /) he wants to perform, then based on the inputs by the user the output will be displayed.

Approach of Program

• First Create a Library to get input from a user
• Create an object
• Take first input from the user
• Take mathematical operation from the user
• Take second input from the user
• Use Switch Case Statement
• Print the output

## Example of Simple Calculator Program in Java

``````//Simple java program for a calulator

//Import Scanner package
import java.util.Scanner;

// Main Class of program
public class Main
{
//Main Function
public static void main(String[] args) {
//creating object for class Scanner
Scanner input = new Scanner(System.in);
//Declaring the variable
double firstNumber,secondNumber;
//Displaying a message to user what to enter
System.out.println("Enter First Number : ");
//Taking first number from user
firstNumber = input.nextDouble();

//Displaying a message to user what to enter
System.out.println("Enter the operation : ");
//Taking opertion from user
char opt = input.next().charAt(0);
//Displaying a message to user what to enter
System.out.println("Enter Second Number : ");
//Taking second number from user
secondNumber = input.nextDouble();

//Declate a variable to store the result
double result;

//switch case to match the entered operation
switch(opt){
case '+':
result = firstNumber + secondNumber;
break;
//If entered operation is subtraction
case '-':
result = firstNumber - secondNumber;
break;
//If entered operation is Division
case '/':
result = firstNumber / secondNumber;
break;
//If entered operation is Multipication
case '*':
result = firstNumber * secondNumber;
break;
//If entered operation is Modulation
case '%':
result = firstNumber % secondNumber;
break;
//If entered operation is not the above all
default:
System.out.printf("Invalid operator");
return;
}
//Print the result
System.out.println(firstNumber+" "+opt+" "+secondNumber+" : "+result);
}

}
``````

Output

``````Enter First Number :
5.4
Enter the operation :
/
Enter Second Number :
2.5
5.4 / 2.5 : 2.16``````

Recommended Posts: