Calculator Coding In JAVA

24 Mar

                              Image

A Calculator

Soon after writing a calculator program in C++ and Visual Basic; I started writing it in JAVA. Initially I felt it was quite tough to write it in a secured environment. But I was amazed to find that it was really very easy. Here I am giving an easy guide to my project work.

Using the calculator

The buttons in calculator appear to push in when activated, as they do in Microsoft Windows application. This is an optical illusion, achieved by changing the shading around the edge of the button.

To use the calculator, the user types the digits of the first number, then an arithmetic operator(/,*,+ or -).then a second number, and then the equal sign(=). The answer is displayed. You can chain to another calculation: The answer automatically becomes the first operand, so you can press another arithmetic operator and key in another number to get the next answer. You can use a decimal point in the numbers you input, but not the exponential notation. The output has a fixed decimal place. Unlike in C++, here in calculator using JAVA, calculator screen display has its buttons activated by mouse and not by keyboard pre-defined shortcuts.

Use of typical keys

MC = Memory Clear sets the memory to 0
MR = Memory Recall uses the number in memory, acts as if you had keyed in that number yourself
MS = Memory Store puts the number on the display into the memory
M+ = Memory Add takes the number on the display, adds it to the memory, and puts the result into memory

The buttons can be handy for doing repeated calculations with a single number. For instance, if you wanted to multiply a bunch of numbers by pi, you could key in the following:

3.14159  MS (stores the number)
4 x MR = (gives you 4 times pi)
25 x 25 x MR = (gives you 25×25 times pi)

The M+ button can be handy for figuring out complicated expressions if you don’t happen to have a scientific calculator. For example, to calculate (5 x 6) + (12 x 2) + (3 x 7), you can do the following:

5 x 6 = (calculator says 30)
MS (stores 30 in memory)
12 x 2 = (calculator says 24)
M+ (takes 24, adds it to 30, stores result 54 in memory)
3 x 7 = (21)
M+ (takes 54, adds 21, stores the result 75)
MR (displays the result 75)

Source Code

/*A CALCULATOR PROGRAMME USING JAVA PROGRAMMING*/
 //Package
package calculator;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//Class
public class cal extends JFrame implements ActionListener
{
  //Global variables
  JButton add1,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,BACKSPACE,CE,C,MC,div,sqrt,MR,mul,per,MS,sub,prop,M,pm,dot,eq;
  JTextField t1,t2;
  double result=0,memory=0,n1=0;
  //Mark the first number for easy calculation
  int first=1;
  //First number for percentage calculation
  double num;
  //Flag for appending digits or starting a new number
  /*1->Appending a digit to the existing number
    2->Taking a new number as input*/
   int opt=2; 
  
  //Flag to mark binary operation for '=' button
  /*0->No Operation
    1->Addtion
    2->Subtraction
    3->Division
    4->Multiplication*/
  int oper1=0,oper2=0;
  //Constructor for cal()
   cal()
   {
   setTitle("Calculator");
    setSize(300,300);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
   initComponents();
  }
   //Function for creating User Interface
  void initComponents()
  {
	  //Main textfield
	  t1 = new JTextField(32);
	  t1.setText("0");
	  add(t1,BorderLayout.NORTH);
                 t1.setHorizontalAlignment(JTextField.RIGHT);
	  JPanel p6 = new JPanel();
	  //Panel 1
	  //Textfield for marking MEMORY operations
	  JPanel p1 = new JPanel();
	  t2 = new JTextField(2);
	  t2.setText(" ");
	  p1.add(t2);
	  BACKSPACE = new JButton("BACKSPACE");
	  BACKSPACE.setForeground(Color.RED);
	  p1.add(BACKSPACE);
	  CE= new JButton("CE");
	  CE.setForeground(Color.RED);
	  p1.add(CE);
	  C = new JButton("C");
	  p1.add(C);
	  C.setForeground(Color.RED);
	  p6.add(p1);
	  //Panel 2
	  JPanel p2 = new JPanel();
	  MC = new JButton("MC");
	  MC.setForeground(Color.RED);
	  p2.add(MC);
	  b7 = new JButton("7");
	  b7.setForeground(Color.BLUE);
	  p2.add(b7);
	  b8= new JButton("8");
	  b8.setForeground(Color.BLUE);
	  p2.add(b8);
	  b9 = new JButton("9");
	  b9.setForeground(Color.BLUE);
	  p2.add(b9);
	  div = new JButton("/");
	  div.setForeground(Color.RED);
	  p2.add(div);
	  sqrt = new JButton("sqrt");
	  sqrt.setForeground(Color.BLUE);
	  p2.add(sqrt);
	  p6.add(p2);
	  //Panel 3
	  JPanel p3 = new JPanel();
	   MR = new JButton("MR");
	  MR.setForeground(Color.RED);
	  p3.add(MR);
	  b4= new JButton("4");
	  b4.setForeground(Color.BLUE);
	  p3.add(b4);
	  b5 = new JButton("5");
	  b5.setForeground(Color.BLUE);
	  p3.add(b5);
	  b6= new JButton("6");
	  b6.setForeground(Color.BLUE);
	  p3.add(b6);
	  mul = new JButton("*");
	  mul.setForeground(Color.RED);
	  p3.add(mul);
	  per = new JButton("%");
	  per.setForeground(Color.BLUE);
	  p3.add(per);
	  p6.add(p3);
	  //Panel 4
	  JPanel p4 = new JPanel();
	  MS = new JButton("MS");
	  MS.setForeground(Color.RED);
	  p4.add(MS);
	  b1 = new JButton("1");
	  b1.setForeground(Color.BLUE);
	  p4.add(b1);
	  b2= new JButton("2");
	  b2.setForeground(Color.BLUE);
	  p4.add(b2);
	  b3 = new JButton("3");
	  b3.setForeground(Color.BLUE);
	  p4.add(b3);
	  sub = new JButton("-");
	  sub.setForeground(Color.RED);
	  p4.add(sub);
	  prop = new JButton("1/x");
	  prop.setForeground(Color.BLUE);
	  p4.add(prop);
	  p6.add(p4);
	   //Panel 5
	  JPanel p5 = new JPanel();
	  M = new JButton("M+");
	  M.setForeground(Color.RED);
	  p5.add(M);
	  b0= new JButton("0");
	  b0.setForeground(Color.BLUE);
	  p5.add(b0);
	  pm= new JButton("+/-");
	  pm.setForeground(Color.BLUE);
	  p5.add(pm);
	  dot= new JButton(".");
	  dot.setForeground(Color.BLUE);
	  p5.add(dot);
	  add1 = new JButton("+");
	  add1.setForeground(Color.RED);
	  p5.add(add1);
	  eq = new JButton("=");
	  eq.setForeground(Color.RED);
	  p5.add(eq);
	  p6.add(p5);
	  p1.setBackground(Color.blue);
	  p2.setBackground(Color.cyan);
	  p3.setBackground(Color.cyan);
	  p4.setBackground(Color.cyan);
	  p5.setBackground(Color.cyan);
	  //Adding all individual panels to main panel6
	  p6.setBackground(Color.LIGHT_GRAY);
      add(p6,BorderLayout.CENTER);
      
	  //Add events
      add1.addActionListener(this);
      b0.addActionListener(this);
      b1.addActionListener(this);
      b2.addActionListener(this);
      b3.addActionListener(this);
      b4.addActionListener(this);
      b5.addActionListener(this);
      b6.addActionListener(this);
      b7.addActionListener(this);
      b8.addActionListener(this);
      b9.addActionListener(this);
      BACKSPACE.addActionListener(this);
      CE.addActionListener(this);
      C.addActionListener(this);
      MC.addActionListener(this);
      div.addActionListener(this);
      sqrt.addActionListener(this);
      MR.addActionListener(this);
      mul.addActionListener(this);
      per.addActionListener(this);
      MS.addActionListener(this);
      sub.addActionListener(this);
      prop.addActionListener(this);
      M.addActionListener(this);
      pm.addActionListener(this);
      dot.addActionListener(this);
      eq.addActionListener(this);
      per.addActionListener(this);
  }
  //Method when ActionListener calls its corresponding routine
  public void actionPerformed(ActionEvent evt)
  {
	 String str;
	 //Action Corresponding to + button
	 if(evt.getSource()==add1)
     {
		 if(first==1)
		 {
			 result=num=Double.parseDouble(t1.getText());
			 oper1=1;
		 }
		 else
		 {
			 n1=Double.parseDouble(t1.getText());
			 oper2=1;
		 }
		 //Action corresponding to previous operator
		 switch(oper1)
		 {
		 case 1:add1();
		 	    break;
		 case 2:sub();
		 		break;
		 case 3:div();
		 		break;
		 case 4:mul();
		 		break;
		 }
	 }
	 //Action Corresponding to * button
	 if(evt.getSource()==mul)
     {
		 if(first==1)
		 {
			 result=num=Double.parseDouble(t1.getText());
			 oper1=4;
		 }
		 else
		 {
			 n1=Double.parseDouble(t1.getText());
			 oper2=4;
		 }
		//Action corresponding to previous operator
		 switch(oper1)
		 {
		 case 1:add1();
		 	    break;
		 case 2:sub();
		 		break;
		 case 3:div();
		 		break;
		 case 4:mul();
		 		break;
		 }
	  }
	//Action Corresponding to / button
	 if(evt.getSource()==div)
     {
		 if(first==1)
		 {
			 result=num=Double.parseDouble(t1.getText());
			 oper1=3;
		 }
		 else
		 {
			 n1=Double.parseDouble(t1.getText());
			 oper2=3;
		 }
		//Action corresponding to previous operator
		 switch(oper1)
		 {
		 case 1:add1();
		 	    break;
		 case 2:sub();
		 		break;
		 case 3:div();
		 		break;
		 case 4:mul();
		 		break;
		 }
	  }
	//Action Corresponding to - button
      else if(evt.getSource()==sub)
      {
    	  if(first==1)
    	  {
    		  result=num=Double.parseDouble(t1.getText());
    		  oper1=2;
    	  }
 		 else
 		 {
 			 n1=Double.parseDouble(t1.getText());
 			 oper2=2;
 		 }
    	//Action corresponding to previous operator
    	  switch(oper1)
 		 {
 		 case 1:add1();
 		 	    break;
 		 case 2:sub();
 		 		break;
 		 case 3:div();
 		 		break;
 		 case 4:mul();
 		 		break;
 		 }
    	 
      }
	//Action Corresponding to = button
	  else if(evt.getSource()==eq)
	  {
		  	  double n1=Double.parseDouble(t1.getText());
			  if(oper1==1)
				  result=result+n1;
			  else if(oper1==2)
				  result=result-n1;
			  else if(oper1==3)
				  result=result/n1;
			  else if(oper1==4)
				  result=result*n1;
			  else
				  result=Double.parseDouble(t1.getText());
			  num=result;
			  str=String.valueOf(result);
			  t1.setText(str);
	  }
	//Action Corresponding to MS button
	  else if(evt.getSource()==MS)
	  {
		  memory=Double.parseDouble(t1.getText());
		  str=String.valueOf("M");
		  t2.setText(str);
		  
	  }
	//Action Corresponding to M button
	  else if(evt.getSource()==M)
	  {
		  memory=memory+Double.parseDouble(t1.getText());
	  }
	//Action Corresponding to MC button
	  else if(evt.getSource()==MC)
	  {
		  memory=0;
		  t1.setText("0");
		  t2.setText(" ");
	  }
	//Action Corresponding to MR button
	  else if(evt.getSource()==MR)
	  {
		  str=String.valueOf(memory);
		  t1.setText(str);
	  }
	//Action Corresponding to +/- button
	  else if(evt.getSource()==pm)
	  {
		  double n1=Double.parseDouble(t1.getText());
		  n1=-n1;
		  str=String.valueOf(n1);
		  t1.setText(str);
	  }
	//Action Corresponding to 0 button
	  else if(evt.getSource()==b0)
	  {
		  if(opt==1)
		      str=String.valueOf(t1.getText())+0;
		  else
			  str=String.valueOf(" ")+0;
		  opt=1;
                  t1.setText(str);  
		 
	  }
	//Action Corresponding to 1 button
	  else if(evt.getSource()==b1)
	  {
		  if(opt==1)
		      str=String.valueOf(t1.getText())+1;
		  else
			  str=String.valueOf(" ")+1;
		  opt=1;
		  t1.setText(str);
		  
	  }
	//Action Corresponding to 2 button
	  else if(evt.getSource()==b2)
	  {
		  if(opt==1)
		     str=String.valueOf(t1.getText())+2;
		  else
			  str=String.valueOf(" ")+2;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to 3 button
	  else if(evt.getSource()==b3)
	  {
		  if(opt==1)
			 str=String.valueOf(t1.getText())+3;
		  else
			 str=String.valueOf(" ")+3;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to 4 button
	  else if(evt.getSource()==b4)
	  {
		  if(opt==1)
		     str=String.valueOf(t1.getText())+4;
		  else
		     str=String.valueOf(" ")+4;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to 5 button
	  else if(evt.getSource()==b5)
	  {
		  if(opt==1)
			str=String.valueOf(t1.getText())+5;
		  else
			str=String.valueOf(" ")+5;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to 6 button
	  else if(evt.getSource()==b6)
	  {
		  if(opt==1)
			str=String.valueOf(t1.getText())+6;
		  else
			str=String.valueOf(" ")+6;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to 7 button
	  else if(evt.getSource()==b7)
	  {
		  if(opt==1)
		    str=String.valueOf(t1.getText())+7;
		  else
		    str=String.valueOf(" ")+7;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to 8 button
	  else if(evt.getSource()==b8)
	  {
		  if(opt==1)
			 str=String.valueOf(t1.getText())+8;
		  else
		     str=String.valueOf(" ")+8;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to 9 button
	  else if(evt.getSource()==b9)
	  {
		  if(opt==1)
			 str=String.valueOf(t1.getText())+9;
		  else
		     str=String.valueOf(" ")+9;
		  opt=1;
		  t1.setText(str);
	  }
	//Action Corresponding to BACKSPACE button
	  else if(evt.getSource()==BACKSPACE)
	  {
		  int len;
		  str=t1.getText();
		  len=str.length();
		  if(len>=1)
		    str=str.substring(0,len-1);
		  t1.setText(str);
	  }
	//Action Corresponding to CE button
	  else if(evt.getSource()==CE)
	  {
		  result=0;
		  first=1;
		  opt=2;
		  str=String.valueOf('0');
		  t1.setText(str);
		  
	  }
	//Action Corresponding to C button
	  else if(evt.getSource()==C)
	  {
		  result=0;
		  memory=0;
		  first=1;
		  opt=2;
		  t1.setText("0");
		  t2.setText(" ");
		  
	  }
	//Action Corresponding to . button
	  else if(evt.getSource()==dot)
	  {
		  str=String.valueOf(t1.getText())+".";
		  t1.setText(str); 
	  }
	//Action Corresponding to 1/x button
	  else if(evt.getSource()==prop)
	  {
		  double n1=Double.parseDouble(t1.getText());
		  n1=1/n1;
		  str=String.valueOf(n1);
		  t1.setText(str); 
	  }
	//Action Corresponding to sqrt button
	  else if(evt.getSource()==sqrt)
	  {
		  double n1=Double.parseDouble(t1.getText());
		  n1=Math.sqrt(n1);
		  str=String.valueOf(n1);
		  t1.setText(str);
	  }
	//Action Corresponding to % button
	  else if(evt.getSource()==per)
	  {
		  double n1=Double.parseDouble(t1.getText());
		  n1=(n1*num)/100;
		  str=String.valueOf(n1);
		  t1.setText(str);
	  }
     
  }
  //Add called according to previous operator
  void add1()
  {
	  if(first==0)
			result=num=result+n1;
		  String str=String.valueOf(result);
		  t1.setText(str);
		  opt=2;
		  if(oper2!=0)
		  {
			  oper1=oper2;
			  oper2=0;
		  }
		  first=0;
  }
//Sub called according to previous operator
  void sub()
  {
	  if(first==0)
		  result=num=result-n1;
	  String str=String.valueOf(result);
	  t1.setText(str);
	  opt=2;
	  if(oper2!=0)
	    oper1=oper2;
	  first=0;
  }
//Div called according to previous operator
  void div()
  {
	  if(first==0)
	  {
		  if(n1==0)
			  t1.setText("Cannot divide by zero");
		  else
			  result=num=result/n1;
	  }
	  String str=String.valueOf(result);
	  t1.setText(str);
	  opt=2;
	  if(oper2!=0)
	    oper1=oper2;
	  first=0;
  }
//Mul called according to previous operator
  void mul()
  {
	  if(first==0)
		  result=num=result*n1;
	  String str=String.valueOf(result);
	  t1.setText(str);
	  opt=2;
	  if(oper2!=0)
	    oper1=oper2;
	  first=0;
  }
  public static void main(String args[])
  {
	cal obj = new cal();
	obj.setVisible(true);
   }
}

Inference

Though coding can be done in a better and compact format, now being a preliminary user; I’ve just focused on coding and java. I’ll soon try and post my upgraded version of the same and varied other programmes of calculator after analyzing time and space complexity of the programme.

Here what I’ve done is that I’ve added buttons onto panels and used 2 textfields – one for integer calculation and the other for marking memory operations.  Textfields could have also been implemented in array fashion for ease.

Method of calculating in calculator has been kept simple as Standard Microsoft Calculators.

Event Handling has been used where a source generates an event and a listener is notified  when an event occurs say when a button is pressed using a mouse.

                                    

Advertisements

7 Responses to “Calculator Coding In JAVA”

  1. xsynos March 24, 2012 at 1:10 pm #

    Good post, keep up the good work. But I would suggest to put the code in a separate frame from where one can get the provisions of copying the code directly.

    • zenithmaniac March 24, 2012 at 1:29 pm #

      Thanks 4 liking…based on your suggestion, i’ve re-framed the source-code in a printable format and can now be easily copied.

  2. phoxis March 25, 2012 at 4:20 am #

    Note the first line of the code, the comment starts ‘/* ‘ but does not end. Here are some issues i have noticed. The computation 2 + 0 = is returning 4. If i enter any number for example 2 and then press = then the answer being displayed is 0, were it should be 2.

    Keep the good work on.

    • zenithmaniac March 25, 2012 at 5:24 am #

      I’ve modified and corrected the code for comment and 2+0=2. but for 2=2 case,in my machine,it is running successfully since beginning. And thanks for liking my work.

  3. AndroidResearch March 25, 2012 at 11:40 am #

    Looks pretty good,
    Good luck in your Java learning journey!

    • zenithmaniac March 25, 2012 at 1:38 pm #

      Thanks 4 encouragement! Recently i had started a project work with Andriod Programming but soon had to stop for lack of knowledge. But now after seeing your blog,it seems i can again restart my work.Great job by you.

      • AndroidResearch March 25, 2012 at 1:40 pm #

        Thank you, hope it will help you put in the right mood! 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: