Tuesday, April 16, 2013

Math Calculator program

This is a simple Java Math Calculator program. The calculator can do addition, subtraction, multiplication, division of two numbers, and squaring, finding sine, cosine, and tangent of a number. The calculator accepts only digit, dot, backspace, and delete keys input. In this program, you will learn how to do the followings in Java:
-creating program interface with JFrame and other controls,
-writing code to enable the controls to perform actions, and
-detecting key typed.

MathCalculator source code:

1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 import javax.swing.event.*;

class  Calculator extends JFrame implements ActionListener{
5          JTextField txtresult;
6          JLabel lblshow;
7          JButton btzero, btone,bttwo,btthree,btfour,btfive,btsix, btseven, bteight, btnine;
8          JButton btadd, btsubtract, btmultiply, btdivide, btclear, btresult,btsquare, btsqrt,btcos,btsin,bttan;
9          JOptionPane dialog;
10        double res;

11        Calculator(){
12        setTitle("Match Calculator");
13        setDefaultCloseOperation(EXIT_ON_CLOSE);
14        setSize(330,200);
15        setResizable(false);
16        setLayout(new FlowLayout());
17        Container cont=getContentPane();
18        dialog=new JOptionPane();
19        lblshow=new JLabel("");
20        lblshow.setSize(20,20);
21        txtresult=new JTextField("0",29);
22        txtresult.addKeyListener(new KeyList());
23        btzero=new JButton("0");
24        btzero.addActionListener(this);
25        btone=new JButton("1");
26        btone.addActionListener(this);
27        bttwo=new JButton("2");
28        bttwo.addActionListener(this);
29        btthree=new JButton("3");
30        btthree.addActionListener(this);
31        btfour=new JButton("4");
32        btfour.addActionListener(this);
33        btfive=new JButton("5");
34        btfive.addActionListener(this);
35        btsix=new JButton("6");
36        btsix.addActionListener(this);
37        btseven=new JButton("7");
38        btseven.addActionListener(this);
39        bteight=new JButton("8");
40        bteight.addActionListener(this);
41        btnine=new JButton("9");
42        btnine.addActionListener(this);43           
43        btadd=new JButton("+");
44        btadd.addActionListener(this);
45        btsubtract=new JButton("-");
46        btsubtract.addActionListener(this);
47        btmultiply=new JButton("*");
48        btmultiply.addActionListener(this);          
49        btdivide=new JButton("/");
50        btdivide.addActionListener(this);
51        btresult=new JButton("=");
52        btresult.addActionListener(this);
53        btclear=new JButton("C");
54        btclear.addActionListener(this);
55        btsquare=new JButton("<html>x<sup>2</sup></html>");
56        btsquare.addActionListener(this);
57        btsqrt=new JButton("sqrt");
58        btsqrt.addActionListener(this);
59        btsin=new JButton("sin");
60        btsin.addActionListener(this);
61        btcos=new JButton("cos");
62        btcos.addActionListener(this);
63        bttan=new JButton("tan");
64        bttan.addActionListener(this);
65        cont.add(lblshow);
66        cont.add(txtresult);
67        cont.add(btzero);
68        cont.add(btone);
69        cont.add(bttwo);
70        cont.add(btthree);
71        cont.add(btfour);
72        cont.add(btresult);
73        cont.add(btclear);
74        cont.add(btfive);
75        cont.add(btsix);
76        cont.add(btseven);
77        cont.add(bteight);
78        cont.add(btnine);
79        cont.add(btadd);
80        cont.add(btmultiply);
81        cont.add(btsqrt);
82        cont.add(btsin);
83        cont.add(btcos);
84        cont.add(bttan);
85        cont.add(btsubtract);
86        cont.add(btdivide);
87        cont.add(btsquare);
88        setVisible(true);
            }

89 public void actionPerformed(ActionEvent e){
            double val;
            txtresult.requestFocus();
            if(txtresult.getText().equals("0")) txtresult.setText("");    

            try{
            if(e.getSource()==btzero) txtresult.setText(txtresult.getText()+btzero.getText());
            else if(e.getSource()==btone) txtresult.setText(txtresult.getText()+btone.getText());
            else if(e.getSource()==bttwo) txtresult.setText(txtresult.getText()+bttwo.getText());
            else if(e.getSource()==btthree) txtresult.setText(txtresult.getText()+btthree.getText());
            else if(e.getSource()==btfour) txtresult.setText(txtresult.getText()+btfour.getText());           
            else if(e.getSource()==btfive) txtresult.setText(txtresult.getText()+btfive.getText());
            else if(e.getSource()==btsix) txtresult.setText(txtresult.getText()+btsix.getText());
            else if(e.getSource()==btseven) txtresult.setText(txtresult.getText()+btseven.getText());
            else if(e.getSource()==bteight) txtresult.setText(txtresult.getText()+bteight.getText());
            else if(e.getSource()==btnine) txtresult.setText(txtresult.getText()+btnine.getText());
            else if(e.getSource()==btadd){
                       
                        calc("+",getVal(txtresult.getText()));
            }
            else if(e.getSource()==btsubtract){
                        calc("-",getVal(txtresult.getText()));
                       
            }
            else if(e.getSource()==btmultiply){
                        calc("*",getVal(txtresult.getText()));
                       
            }
            else if(e.getSource()==btdivide){
                        calc("/",getVal(txtresult.getText()));
            }
            else if(e.getSource()==btresult){
                        calc("",Double.parseDouble(txtresult.getText()));
                        txtresult.setText(""+res);
                        lblshow.setText("");
            }
            else if(e.getSource()==btsquare){
                        res=Math.pow(getVal(txtresult.getText()),2);
                        txtresult.setText(""+res);
                       
            }
            else if(e.getSource()==btsqrt){
                        res=Math.sqrt(getVal(txtresult.getText()));
                        txtresult.setText(""+res);
                       
            }
            else if(e.getSource()==btsin){
                        res=Math.sin(getVal(txtresult.getText()));
                        txtresult.setText(""+res);
                       
            }
            else if(e.getSource()==btcos){
                        res=Math.cos(getVal(txtresult.getText()));
                        txtresult.setText(""+res);
                       
            }
            else if(e.getSource()==bttan){
                        res=Math.tan(getVal(txtresult.getText()));
                        txtresult.setText(""+res);
                       
            }
            else if (e.getSource()==btclear){
                        txtresult.setText("0");
                        lblshow.setText("");
                       
            }
     }catch(Exception ex){
                        dialog.showMessageDialog(this, "Bad calculation!","Error",JOptionPane.ERROR_MESSAGE);
                        txtresult.setText("0");
            }
}          

90 public class KeyList extends KeyAdapter{
            public void keyTyped(KeyEvent ke){
           
                        char c = ke.getKeyChar();
                        int intkey=(int)c;
                        if(txtresult.getText().equals("0")) txtresult.setText("");
                        if(!(intkey>=48 && intkey<=57 || intkey==46 || intkey==8 || intkey==127))
                         {
                                    ke.consume();
                                    if(intkey==43) calc("+",getVal(txtresult.getText()));
                                    else if(intkey==45) calc("-",getVal(txtresult.getText()));
                                    else if(intkey==42) calc("*",getVal(txtresult.getText()));
                                    else if(intkey==47) calc("/",getVal(txtresult.getText()));
                                    else if(intkey==10) {
                         
                                                calc("",getVal(txtresult.getText()));
                                                txtresult.setText(""+res);
                                                lblshow.setText("");

                                    }
                         }
                       
             }
}


91 public void calc(String sig, double nextval){
            String prerecord=lblshow.getText();
            if(prerecord.equals("")) res=nextval;
            else{
                        String sign=prerecord.substring(prerecord.length()-1);
                        double preval=Double.parseDouble(prerecord.substring(0,prerecord.length()-1));           
                        if(sign.equals("+")) res=nextval+preval;
                        else if(sign.equals("-"))  res=preval-nextval;
                        else if(sign.equals("*")) res=preval*nextval;
                        else res=preval/nextval;
           
            }
            lblshow.setText(res+sig);
            txtresult.requestFocus();
            txtresult.setText("");
            }

92 public double getVal(String val){
                        if (val.equals("")) return 0.0;
                        else return (Double.parseDouble(val));
            }
}


93 public class MathCalculator{
 
public static void main(String args[]){
     new Calculator();
  
}


}


Code Explanation:
1-4 include classed needed to draw calculator interface.
5 Delare variable txtresult of JTextField type. The JTextField txtresult acts as and entry point of the calculator program.
6 Delare variable lblshow of JLabel type. The lblshow label is used to track the result of calcuations. 
7 Declare variables: btzero, btone,bttwo,btthree,btfour,btfive,btsix, btseven, bteight, btnine of JButton type. These variables will reference to button labeled 0, labeled 1,labeled 2,labeled 3,labeled 4,labeled 5,labeled 6, labeled 7,labeled 8,labeled 9 on the program interface.
8 Declare variables: btadd, btsubtract, btmultiply, btdivide, btclear, btresult,btsquare, btsqrt,btcos,btsin,bttan. They refer to button labeled +, labeled -,   labeled *,  labeled /,  labeled C, labeled =, labeled x*x,  labeled sqrt,  labeled sin,  labeled cos, and labeled tan on the program interface.
9 Declare variable dialog of JOption pane type. This variable refers to the dialog box to inform the user when an invalid calculation occurs.
10 Declare variable res of Double type to store the result of any calculation.
11-88 Design the program interface. For more detail, you may need to read code explanation of the Text Editor program.  
89 To able a button to perform an action when it is clicked, the actionPerformed method of the ActionListener interface has to be rewritten. When a numbering button is clicked the text on the button is appended to text box txtresult. This task can be done by concatenating the existing value of the text box and the text on the clicked button. When a calculation button (addition, subtraction,...) is clicked the calc method is called to perform the calculation.
90 The KeyList class extends KeyAdapter class. The KeyAdpater class has the keyTyped method that can be rewritten  to detect key input. 
Each character key input is converted to its integer number equivalent. Then this number is checked to determine whether it is numerical (between 48 and 57), dot (46), backspace (8), or delete (127) key.
The key that is not in the acceptable range is not shown in the text box. However, some hidden keys that are needed such as +,-,*/, and ENTER keys are tracked. These keys can be used to perform operations the same as button +, button -, button *, button /, and button = on the window interface. 
91 The calc method defines code to do a calculation. It is invoked when a button to perform the calculation is clicked or when the key to perform the option is typed. 
92  The getVal method is invoked to get and convert the number in txtresult text  to a double type.
93 The MathCalculator class contain the main method to start the program.

No comments:

Post a Comment