15) Write a Java program to simulate the arithmetic calculator (+ ,- ,* , /).Also add 2 buttons namely ‘on’ to start the calculator and ‘clear’ to clear the text box.Display appropriate error message in the text box.


import java.awt.*;

import java.awt.event.*;

public class CalAwt extends Frame implements ActionListener
{
Button on,clear,addn,subn,muln,divn,end,equal;
TextField input;
Panel pan1,pan2,pan3;
double no1,no2;
double ans;
char oper;

public CalAwt()
{
pan1= new Panel();
pan2=new Panel();
pan3=new Panel();
addn=new Button(“+”);
subn=new Button(“-”);
muln=new Button(“*”);
divn=new Button(“/”);
equal=new Button(“=”);
end=new Button(“Exit”);
on=new Button(“On”);
clear=new Button(“Clear”);
input=new TextField(10);
pan2.add(addn);
pan2.add(subn);
pan2.add(muln);
pan2.add(divn);
pan2.add(equal);

pan3.add(on);
pan3.add(clear);
pan3.add(end);

setLayout(new BorderLayout());
pan1.add(input);
add(pan1,”North”);
add(pan2,”Center”);
add(pan3,”South”);

input.setEnabled(false);
addn.setEnabled(false);
subn.setEnabled(false);
muln.setEnabled(false);
divn.setEnabled(false);

addn.addActionListener(this);
subn.addActionListener(this);
muln.addActionListener(this);
divn.addActionListener(this);
equal.addActionListener(this);
end.addActionListener(this);
on.addActionListener(this);
clear.addActionListener(this);

setTitle(“ArithMetic Calculator”);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new CalAwt();

}
public void actionPerformed(ActionEvent e)
{
Button btn= (Button)e.getSource();
if(btn==end)
{
System.exit(0);
}
if(btn==addn || btn==subn || btn==muln || btn==divn)
{
no1=Double.parseDouble(input.getText());
oper=btn.getLabel().charAt(0);
input.setText(“”);
input.requestFocus();
}
if(btn==equal)
{
no2=Double.parseDouble(input.getText());
switch(oper)
{
case ‘+’ :
ans=no1 + no2;
break;
case ‘-’ :
ans=no1 – no2;
break;
case ‘*’ :
ans=no1 * no2;
break;
case ‘/’ :
ans=no1 / no2;
break;
}
input.setText(Double.toString(ans));
}
if(btn==clear)
{
input.setText(“”);
no1=0;
no2=0;
input.requestFocus();
}
if(btn==on)
{
input.setEnabled(true);
addn.setEnabled(true);
subn.setEnabled(true);
muln.setEnabled(true);
divn.setEnabled(true);

}

}
}

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