Creating a Calculator program in Java

0
2026
A brief Introduction to java classes
Simple Java inheritance example

Java, being a power full language, contributes in many technology fields. It has deep contribution in the modern world. A basic calculator program in java can perform logical computations and displays the output. Getting curious about how it works?
You can Download the Source Code Below of see the code live.
downloadHere’s the code:

// Title: CALCULATOR 
// Environment : Java
// Programming Tunes
import java.util.Scanner; // Scanner class used to take input
class Calculator
{
	public static void main (String[] args)
	{
		//'n' as a Scanner class object with "System.in" as constructor argument
		Scanner n = new Scanner(System.in);
		int operand_1,operand_2,menuChoice, result;

		while (true)
		{
			System.out.println("nn---------MENU---------");
			System.out.println("t1.addition");
			System.out.println("t2.subtraction");
			System.out.println("t3.division");
			System.out.println("t4.multiplication");
			System.out.print("t5.Exit Program");
			System.out.print("nt.Enter Choice : ");
			menuChoice = n.nextInt(); // n.nextInt() function takes integer input

			if (menuChoice==5)
				System.exit(1); // terminate program

			System.out.print("Enter First Operand :");
			operand_1 = n.nextInt(); 

			System.out.print("Enter First Operand :");
			operand_2 = n.nextInt();


			switch(menuChoice)
			{
			case 1:
			{ 
				result = operand_1 + operand_2 ;
				System.out.print("Sum :" + result );
				break;
			} // end case 1

			case 2:
			{ 
				result = operand_1 - operand_2 ;
				System.out.print("Difference :" + result );
				break;
			} // end case 2

			case 3:
			{ 
				result = operand_1 / operand_2 ;
				System.out.print("Division :" + result );
				break;
			} // end case 3

			case 4:
			{ 
				result = operand_1 * operand_2 ;
				System.out.print("Product :" + result );
				break;
			}  // end case 4

			case 5:
			{ 
				System.out.print("Safe Exit" );
				System.exit(1);
				break;
			}  // end case 5

			default:
			{
				System.out.print("Invalid Input, try again");
				break;
			}  // end default

			} // end switch

		} // end while loop

	} // end main

} // end Calculator class

The above code provides basic calculations like addition, subtraction, multiplication and division. The main function act as a menu for the calculator program. First step is to select a menu option, then it takes two operands and calculates its result. The program will run again and again until the exit is option is selected. Calculator Program in Java output is shown below:
calculator in java output

A brief Introduction to java classes
Simple Java inheritance example

Leave a Reply