-->

How to Create a Simple Calculator Program using Java Programming Language?

Here we are creating Calculator Program using the Java Programming language.

This is one of the simplest program a beginner can write and understand a lot about computer programming.

The Calculator Program that we are writing here will work on two numbers and it will support Addition, Subtraction, Multiplication and Division operations.

Program Source Code : Calculator.Java

 1 package calculator;
 2 import java.util.Scanner;
 3 
 4 public class Program {
 5 
 6     public static void main(String[] args) {
 7         
 8         char operator;
 9         double num1,num2;
10         Scanner input = new Scanner(System.in);
11         
12         System.out.println("Enter the Operator ( +, -, *, / )");
13         operator = input.next().charAt(0);
14         
15         System.out.println("Enter the two numbers one by one");
16         num1 = input.nextDouble();
17         num2 = input.nextDouble();
18         
19         input.close();
20         
21         switch( operator ) {
22             case '+':
23                 System.out.printf("%.2f + %.2f = %.2f", num1,num2,(num1+num2));
24                 break;
25                 
26             case '-':
27                 System.out.printf("%.2f - %.2f = %.2f", num1,num2,(num1-num2));
28                 break;
29                 
30             case '*':
31                 System.out.printf("%.2f * %.2f = %.2f", num1,num2,(num1*num2));
32                 break;
33             
34             case '/':
35                 if( num2 != 0 )
36                     System.out.printf("%.2f / %.2f = %.2f", num1,num2,(num1/num2));
37                 else
38                     System.out.println("Divide by Zero Situation");
39                 break;
40                 
41             default:
42                 System.out.printf("%c is an invalid operator",operator);
43         }
44     }
45 }

Program Output : Run 1

Enter the Operator ( +, -, *, / ) :
+
Enter the two Numbers one by one : 10 20
10.00 + 20.00 = 30.00

Program Output : Run 2

Enter the Operator ( +, -, *, / ) :
-
Enter the two Numbers one by one : 10 30
10.00 - 30.00 = -20.00

Program Output : Run 3

Enter the Operator ( +, -, *, / ) :
*
Enter the two Numbers one by one : 10 50
10.00 * 50.00 = 500.00

Program Output : Run 4

Enter the Operator ( +, -, *, / ) :
/
Enter the two Numbers one by one : 10 20
10.00 / 20.00 = 0.50

Program Output : Run 5

Enter the Operator ( +, -, *, / ) :
/
Enter the two Numbers one by one : 50 0
Divide by Zero situation

Program Output : Run 6

Enter the Operator ( +, -, *, / ) :
?
Enter the two Numbers one by one : 10 20
? is an invalid Operator

Video Tutorial : How to Write a Simple Calculator Program using Java Programming language