Saturday, 16 March 2013

Basic Calculator program in Java

I guess we are ready to write some good quality basic Java programs. One thing i would like to state here is that even if you are finding Java a bit new, you will eventually master it only by practice and hence it is essential to keep writing codes and not just understanding the theory.

        Let write a very basic Java program for calculator. There is no GUI involved since we have not covered Swing yet. This program will just take two numbers as input and perform the required operations like addition, subtraction etc.  Though it is basic it will cover most of the topics we have learned till now. I am writing and running Java programs on Eclipse and hence you may find it's snapshots here but you can even write codes and execute using command line or use other IDE's like Netbeans. So lets get started.

Java code for Calculator

      Lets first create a class where we implement the calculator logic.Create a new Java project in Eclipse called Calculator. Next create a package in it called basicCalculator. In this package make two new classes
class Calculation where we would implement the calculator logic and class ProgramLauncher which will have the main() function from which we will create class Calculation object and execute it.

Create class Calculation and insert the code below.

package basicCalculator;

import java.util.Scanner;

public class Calculation {

    private float firstOperannd;
    private float secondOperannd;
    private float result;
    private int operator;
    private Scanner input = new Scanner(System.in);
    private boolean exitCalculator = false;

    public void startCalculator() {
        while (!exitCalculator) {

            System.out.println("Enter 1 for addition \n"
                    + "Enter 2 for subtraction \n"
                    + "Enter 3 for multiplication \n"
                    + "Enter 4 for division \n" + "Enter 0 for Exit : ");
            operator = input.nextInt();

            switch (operator) {
            case 1:
                result = add();
                System.out.println("Result is " + result);
                break;

            case 2:
                result = subtract();
                System.out.println("Result is " + result);
                break;

            case 3:
                result = multiply();
                System.out.println("Result is " + result);
                break;

            case 4:
                result = divide();
                System.out.println("Result is " + result);
                break;

            case 0:
                exitCalculator = true;
                System.out.println("Calculator program Terminated \n");
                break;

            default:
                System.out.println("Please provide proper input \n");

            }
        }
    }

    private float add() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd + secondOperannd;
    }

    private float subtract() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd - secondOperannd;
    }

    private float multiply() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd * secondOperannd;
    }

    private float divide() {
        System.out.println("Enter first number : ");
        firstOperannd = input.nextInt();
        System.out.println("Enter second number : ");
        secondOperannd = input.nextInt();
        return firstOperannd / secondOperannd;
    }

}
  There are many point that need to be explained here so be patient. First lets get our code up and running.
So create next class class ProgramLauncher and insert the code below.


package basicCalculator;

public class ProgramLauncher {

    public static void main(String[] args) {

        Calculation calculator = new Calculation();
        calculator.startCalculator();

    }

}

    Just execute the program and try check the output for various test cases. For how to create a project, package , class, how to see standard output in eclipse please go through our post on Hello World.

When you execute this program you will see output something like below - 


 It clearly says what you need to input and what are the corresponding operations. If you press 0 program will terminate. Go ahead and try out various cases.More importantly try division by 0 or something like 0/0. I will explain these but you can go ahead and try it now.


Sample outputs


Understanding the Code

      Launcher code is very simple. All we do is create a Calculation class object and call the startCalculator() method. Just for the record we could call the method like calculator.startCalculator(); because the method is defined to be public. You can't do the same with other functions like add() as they are private. We will explain why we have taken such a decision but till then understand the program behavior.

    Lets go to our calculator logic code now.


Initializations



         We have defined two float operands firstOperannd and secondOperand.Similarly we have defined float result to store result, int operator to store values corresponding to various opearations and finally a scanner object to take use input. Again note that all these are instance variables and are private.So at any point of time you cannot access them using class Calculation object. They can only be manipulated using public functions provided. We also have exitCalculator to keep track whether to exit our program or not. Default value is set to false which means do not close the program unless user says so.

startCalculator() function

     Inside this function we have a while loop which keeps on executing unless exitCalculator is set to true.
Inside the loop we ask user to choose which operation he is interested in. He must input one of the available options i.e 0,1,2,3 or 4. We then have the switch statement which has operator as the argument. 

   Note : Switch statement supports String as argument only in JSE 7 . So i have used int to make the program run for everyone but if you are using  Java SE 7 you can go ahead and use String as input directly.

     Inside the switch statements we have cases each corresponding to different operations.We have defined separate functions for each operation i.e add(),subtract() etc and all we do in each case in switch statement is call these functions. Note the usage of break statement. We are computing the result in each case and printing the same on standard output.Each function computes the result and returns it back. Note that if user enters 0 then exitCalculator is set to true and the program terminates. For all other inputs default statement is executed which says you must provide correct input. Execution will continue unless user enter 0.

Why are functions like add() defined private?

         Before you define anything in Java or for that matter any programming language you must decide what is it going to be used for. Like in this case we know that add() function will only be used by

startCalculator() method and we don't want to allow any usage like objectName.add(). Hence functions are defined to be private. These functions can only be used in other functions of the same class.

Interesting cases

     Lets discuss some of the interesting cases that might arise in case of division.
  • 4/0 : What happens when i divide any number by 0. Technically you can't divide by 0 and you must get an error. You will get an error if you divide by zero in case on integers but in case of float you will get result as infinity. Note if you are using your firstOperand and secondOperand as int's you need to handle that divide by 0 runtime exception. Also if you use int and user types in something like 4.2 it will be truncated to 4.
  • 0/0: What happens when you divide 0 by a 0. Definitely not infinity in this case. Its a value called  NaN(not a number). Again if you use int you will get a runtime exception and program will terminate.These are some of the reasons why we have chosen float over int.


    Eclipse output snapshots



Output for 6/0 operation

Output for 0/0 operation


Do post any doubts you have in the comments sections.

6 comments:

  1. thank you very much this really help me :D

    ReplyDelete
  2. Programming is very interesting and creative thing if you do it with love. Your blog code helps a lot to beginners to learn programming from basic to advance level. I really love this blog because I learn a lot from here and this process is still continuing.
    Love from Pro Programmer

    ReplyDelete
  3. Programming is combination of intelligent and creative work. Programmers can do anything with code. The entire Programming tutorials that you mention here on this blog are awesome. Beginners Heap also provides latest tutorials of Programming from beginning to advance level.
    Be with us to learn programming in new and creative way.

    ReplyDelete
  4. this is not simple classes program

    ReplyDelete
  5. Thanks so much for this help...
    It's very interesting

    ReplyDelete

t> UA-39527780-1 back to top