Thursday 23 June 2011

Java Program to make a Simple Calculator


Open notepad or any text editor and type this code.

import java.io.*;

class cal
  {
    public static void main(String args[]) throws IOException
     {  String a,b,c;
        int s;
        BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the 1st no. :- ");
        a=ob.readLine();       
        System.out.println("Enter the 2nd no. :- ");             
        b=ob.readLine();
        System.out.println("Enter the Choice"+"\n"+"1 for Addition"+"\n"+"2 for  
          Subtraction"+"\n"+"3 for Multiplication"+"\n"+"4 for Division");
        c=ob.readLine();
        s=Integer.parseInt(c);
      int r;
        switch (s)
        {     
        case 1:
        r=Integer.parseInt(a)+Integer.parseInt(b);
          System.out.print("result is:  "+r);
          break;
        case 2:
        r=Integer.parseInt(a)-Integer.parseInt(b);
          System.out.print("result is:  "+r);
          break;
        case 3:
        r=Integer.parseInt(a)*Integer.parseInt(b);
          System.out.print("result is:  "+r);
          break;
        case 4:
        r=Integer.parseInt(a)/Integer.parseInt(b);
          System.out.print("result is:  "+r);
          break;
        default:
        System.out.print("Wrong Choice");
        break;
        }
     }
  }    

and save this file as cal.java in the bin directory (c:\j2sdk1.4.2\bin).

Now open command prompt and go to your Java directory.
Now compile your  program by typing  javac cal.java
Now the program will be compiled.
Now Run your program by typing  java cal

The output of the above program will be like this.

No comments:

Post a Comment