Thursday, February 27, 2014

A calculator program with java





Step 1:-

Save the file calculator.java


………………………………………………………………………………………

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class calculator extends Applet
implements ActionListener
{
        TextField t1,t2,t3;
        Label l1,l2,l3;
        Button b1,b2,b3;

        public void init()
        {
                l1=new Label("1st input");
                add(l1);
                t1=new TextField(20);
                add(t1);

                l2=new Label("2nd input");
                add(l2);
                t2=new TextField(20);
                add(t2);

                l3=new Label("result");
                add(l3);
                t3=new TextField(20);
                add(t3);

                b1=new Button("Add");
                add(b1);
                b1.addActionListener(this);

                b2=new Button("Subtract");
                add(b2);
                b2.addActionListener(this);

                b3=new Button("Multiply");
                add(b3);
                b3.addActionListener(this);
               


        }

        public void actionPerformed(ActionEvent e)
        {       int a=Integer.parseInt(t1.getText());
                int b=Integer.parseInt(t2.getText());
                int c;
                if(e.getSource()==b1)
                {
                      c=a+b;
                      t3.setText(String.valueOf(c));
                }
                if(e.getSource()==b2)
                {
                      c=a-b;
                      t3.setText(String.valueOf(c));
                }
                if(e.getSource()==b3)
                {
                      c=a*b;
                      t3.setText(String.valueOf(c));
                }

               

        }

}

For Compilation type :- javac calculator.java
…………………………………………………………………………

Step 2: Html file
Save the file calculator.html

<applet code="calculator.class" width=200 height=200>
</applet>

……………………………………………………………………….


Step 3: Output of the program

To run the program type:- appletviewer calculator.java

                                            

No comments:

Post a Comment