Simple Calculator Program in Java

Simple Calculator Program in Java | Previously we had developed many basic Java programs on flow control statements. In this post, we will create a simple calculator program in the Java programming language. It will be a basic calculator in java with CUI (character user interface). It can add, subtract, multiply, divide, find the remainder and also find the power of the number.

First we will develop simple calculator program in java using switch case statements. The switch case statement in Java programming is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly. Two keywords are used in the program:- switch and case.

If you choose the data type of input variables as integer type (int/long) then the calculator doesn’t work on floating-point numbers so we should choose the variables as a double data type. The double data type can hold both integer and floating-point numbers.

It is good programming practice to place all variables declaration at the top of the methods so programmers can easily understand. It is always recommended to initialize all the local variables with their default values.

Simple calculator program in Java using switch case

import java.util.Scanner;

public class BasicCalculator {

   public static void main(String[] args) {

      // Declare variables
      double num1=0.0, num2=0.0;
      char operator='\0';

      // create Scanner class object to  
      // read inputs
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter two numbers: ");
      num1 = scan.nextDouble();
      num2 = scan.nextDouble();

      // read operator
      System.out.println("Available Operators"
		+ "are::  (+ - * / % ^)");
      System.out.print("Enter operator: ");
      operator = scan.next().charAt(0);

      // switch-case statements
      switch(operator) {

         case '+':
            System.out.println("Result = "+ (num1+num2));
		break;

	 case '-':
	    System.out.println("Result = "+ (num1-num2));
		break;

	 case '*':
	    System.out.println("Result = "+ (num1*num2));
		break;

	 case '/':
	    System.out.println("Result = "+ (num1/num2));
		break;

	 case '%':
	    System.out.println("Result = "+ (num1%num2));
		break;

	 case '^':
	    System.out.println("Result = "+ 
                               Math.pow(num1,num2));
		break;

	 default:
	    System.out.println("Invalid operator");
      } // end of switch-case

      // close Scanner class object
      scan.close();

   } 
}

The output for the different test-cases:-

Enter two numbers: 10 20
Available Operatorsare:: (+ – * / % ^)
Enter operator: +
Result = 30.0

Enter two numbers: 25.2 15
Available Operatorsare:: (+ – * / % ^)
Enter operator: –
Result = 10.2

Enter two numbers: 19 4
Available Operatorsare:: (+ – * / % ^)
Enter operator: %
Result = 3.0

Enter two numbers: 2 5
Available Operatorsare:: (+ – * / % ^)
Enter operator: ^
Result = 32.0

We have successfully developed a simple basic calculator in Java using switch case statements. Now, we will do add some extra codes to this program.

1) We should perform every operations through methods. In the above java program we directly done every operations like addition, subtraction e.t.c using operators, but we shouldn’t do that. These code for different operations should be placed in a different method. So, for every operations (like addition, subtraction, multiplication, division, finding remainder, and calculating power) there will be seprate methods.

2) After performing one operation (like addition) Java completes, it doesn’t ask that “Do you want to next operation?”. Due to this, after addition, if we want to subtract then again we need to run the program. The program should ask for input until the end-user wants to continue. For this purpose we should use a loop.

3) We are directly displaying the available operator. It is possible that the end-user doesn’t know which operator will do what operation. So, we should develop a calculator program in java as Menu driven program.

import java.util.Scanner;

public class Calculator {

   public static void main(String[] args) {
      // declare variables
      double num1=0.0, num2=0.0;
      double sum=0.0, sub=0.0, multiple=0.0;
      double divide=0.0, remainder=0.0, power=0.0;
      char operator='\0';
      boolean nextOperation = true;
      char ch='\0';

      // create Scanner class object to  
      // read inputs
      Scanner scan = new Scanner(System.in);

      // loop to repeat the process
      while(nextOperation) {

         // read numbers
         System.out.print("Enter two numbers: ");
         num1 = scan.nextDouble();
         num2 = scan.nextDouble();

         // read operation
         System.out.println("Which operation "
		+ "do you want to perform? \n"
		+ "Options are:- \n"
		+ "1. Addition \n"
		+ "2. Subtraction \n"
		+ "3. Multiplication \n"
		+ "4. Division \n"
		+ "5. Remainder \n"
		+ "6. Power value \n"
		+ "7. Exit");
         System.out.print("Enter option number: ");
         operator = scan.next().charAt(0);

         // switch-case
         switch(operator) {

            case '1':
               sum = add(num1, num2);
               System.out.println(num1 + " + "
			+ num2 + " = " + sum);
               break;

            case '2':
               sub = subtract(num1, num2);
               System.out.println(num1 + " - "
			+ num2 + " = " + sub);
               break;

            case '3':
               multiple = multiply(num1, num2);
               System.out.println(num1 + " * "
			+ num2 + " = " + multiple);
               break;

            case '4':
               divide = division(num1,num2);
               System.out.println(num1 + " / "
			+ num2 + " = " + divide);
               break;

            case '5':
               remainder = findRemainder(num1, num2);
               System.out.println(num1 + " % "
			+ num2 + " = " + remainder);
               break;

            case '6':
               power = Math.pow(num1, num2);
               System.out.println(num1 + " ^ "
			+ num2 + " = " + power);
               break;

            case '7':
               // Shutdown JVM
               System.exit(0); 

            default:
               System.out.println("Invalid operator");
         } // end of switch-case

         // ask for continue
         System.out.println("\nDo you want to continue?");
         System.out.print("Enter Y/N:: ");
         ch = scan.next().charAt(0);

         // continue when user enter 'y' or 'Y'
         // convert input into upper-case and check
         if(Character.toUpperCase(ch)!='Y')
         nextOperation = false;

         System.out.println(); // space
      } // while loop

      System.out.println("Thank You.");

      // close Scanner class object
      scan.close();
   }

   // method to calculate addition of two numbers 
   public static double add(double num1, double num2) {
      return num1 + num2;
   }

   // method to calculate subtraction of two numbers 
   public static double subtract(double num1, double num2){
      return num1 - num2;
   }

   // method to calculate multiplication of two numbers 
   public static double multiply(double num1, double num2){
      return num1 * num2;
   }

   // method to calculate division of two numbers 
   public static double division(double num1, double num2){
      return num1 / num2;
   }

   // method to calculate remainder of two numbers 
   public static double findRemainder(double num1, 
                                       double num2) {
      return num1 % num2;
   }
}

The Output for different test-cases:-

Enter two numbers: 10 20
Which operation do you want to perform?
Options are:-
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Remainder
6. Power value
7. Exit
Enter option number: 1
10.0 + 20.0 = 30.0

Do you want to continue?
Enter Y/N:: y

Enter two numbers: 15 5
Which operation do you want to perform?
Options are:-
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Remainder
6. Power value
7. Exit
Enter option number: 2
15.0 – 5.0 = 10.0

Do you want to continue?
Enter Y/N:: y

Enter two numbers: 12 5
Which operation do you want to perform?
Options are:-
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Remainder
6. Power value
7. Exit
Enter option number: 5
12.0 % 5.0 = 2.0

Do you want to continue?
Enter Y/N:: n

Thank You.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *