How to make a calculator in Java
Java is a programming language widely used in various domains, including enterprise software development, web development, Android app development, scientific applications, and more.
Let's build a simple calculator in Java that can perform the following mathematical operations:
Addition
Subtraction
Multiplication
Division
Following is the coding example of a program written in java to perform the above mentioned mathematical operations.
Note: In the playground provided below, you are required to input two numbers followed by an arithmetic operation to be performed on those numbers. Please follow the format of entering the inputs as shown: "1 2 +".
Coding example
import java.io.*;import java.lang.*;import java.lang.Math;import java.util.Scanner;public class Calculator {public static void main(String[] args){// Stores two numbersdouble a, b;// Take input from the userScanner scn = new Scanner(System.in);System.out.println("Enter the numbers:");// Take the inputsa = scn.nextDouble();b = scn.nextDouble();System.out.println("Enter the arithmetic operator (+,-,*,/):");char op = scn.next().charAt(0);double output = 0;switch (op) {// case to add two numberscase '+':output = a + b;break;// case to subtract two numberscase '-':output = a - b;break;// case to multiply two numberscase '*':output = a * b;break;// case to divide two numberscase '/':output = a / b;break;default:System.out.println("You enter wrong input");}System.out.println("Result:");System.out.println(a + " " + op + " " + b + " = " + output);}}
Enter the input below
Explanation
Lines 10–19: The program starts by declaring variables
aandbto store the two numbers that the user will input. It then prompts the user to enter the numbers using theScannerclass and the inputs are stored inaandb.Lines 21–23: Next, the program prompts the user to enter an arithmetic operator (
+,-,*, or/) to choose the desired operation. The operator input is stored in the variableop.Lines 24–49: The program uses a
switchstatement to perform the selected arithmetic operation. Depending on the value ofop, it adds (+), subtracts (-), multiplies (*), or divides (/) the numbersaandb. The result is stored in the variableoutput.Lines 51–55: Finally, the program displays the final result by printing the original numbers
aandb, the chosen operatorop, and the calculated resultoutput.
Following is the output of the above program.
Enter the numbers:Enter the arithmetic operator (+,-,*,/):Result:1.0 + 2.0 = 3.0
Free Resources