In this post, we will see how to create a simple calculator in java.
This calculator program performs 4 basic operatios – Addition, Substraction, Multiplication and division.It uses Switch case to choose operation you want to perform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import java.util.Scanner; public class Calculator { public static void main(String args[]) { float num1, num2, result; char operation, ch; Scanner scan = new Scanner(System.in); do { System.out.print("1. Addition\n"); System.out.print("2. Subtraction\n"); System.out.print("3. Multiplication\n"); System.out.print("4. Division\n"); System.out.print("5. Exit\n\n"); System.out.print("Enter your operation : "); operation = scan.next().charAt(0); switch(operation) { case '1' : System.out.print("Enter Two Number : "); num1 = scan.nextFloat(); num2 = scan.nextFloat(); result = num1 + num2; System.out.print("Addition of numbers is " + result); break; case '2' : System.out.print("Enter Two Number : "); num1 = scan.nextFloat(); num2 = scan.nextFloat(); result = num1 - num2; System.out.print("Subtraction of numbers is " + result); break; case '3' : System.out.print("Enter Two Number : "); num1 = scan.nextFloat(); num2 = scan.nextFloat(); result = num1 * num2; System.out.print("Multiplication of numbers is " + result); break; case '4' : System.out.print("Enter Two Number : "); num1 = scan.nextFloat(); num2 = scan.nextFloat(); result = num1 / num2; System.out.print("Division of numbers is " + result); break; case '5' : System.exit(0); break; default : System.out.print("Wrong operation!!!"); break; } System.out.print("\n---------------------------------------\n"); }while(operation != 5); } } |
Output:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. ExitEnter your operation : 3
Enter Two Number : 5 7
Multiplication of numbers is 35.0
—————————————
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. ExitEnter your operation : 1
Enter Two Number : 55 25
Addition of numbers is 80.0
—————————————
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. ExitEnter your operation : 5
2. Subtraction
3. Multiplication
4. Division
5. ExitEnter your operation : 3
Enter Two Number : 5 7
Multiplication of numbers is 35.0
—————————————
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. ExitEnter your operation : 1
Enter Two Number : 55 25
Addition of numbers is 80.0
—————————————
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. ExitEnter your operation : 5
That’s all about java program to make simple calculator.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.