Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception Display the exception in a message dialog box.
Program Code:
import java.awt.*;
import java.awt.event.*;
class NumDiv extends Frame implements ActionListener
{
TextField num1, num2, res;
Button division;
String msg=" ";
Label l1,l2;
NumDiv()
{
l1=new Label("Enter First Number");
l2=new Label("Enter Second Number");
num1=new TextField(30);
num2=new TextField(30);
res=new TextField(100);
division=new Button("Division");
setLayout(null);
setForeground(Color.blue);
setFont(new Font("Ariel", Font.BOLD,15));
l1.setBounds(100,100,200,30);
l2.setBounds(100,150,200,30);
num1.setBounds(350,100,100,30);
num2.setBounds(350,150,100,30);
division.setBounds(200,200,100,30);
res.setBounds(100,250,300,30);
add(l1); add(num1);
add(l2); add(num2);
add(res);
add(division);
setSize(600,600);
setVisible(true);
setTitle("DIvision");
setBackground(new Color(250,160,250));
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
division.addActionListener(this);
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.setFont(new Font("Arial",Font.BOLD,30));
}
public static void main(String[] args)
{
new NumDiv();
}
public void actionPerformed(ActionEvent e)
{
msg="";
int n1=1;int n2=1;int temp=1;
String s1=num1.getText();
String s2=num2.getText();
try
{
n1=Integer.parseInt(s1);
n2=Integer.parseInt(s2);
}
catch(NumberFormatException ex)
{
MyDialog d=new MyDialog(this, "NumberFormatException Dialog",ex);
}
if(n2==0)
{
try{ temp=n1/n2; } catch(ArithmeticException e1) { MyDialog d=new
MyDialog(this,"ArithmaticExceptionDialog",e1); }
}
else
{
msg+=n1/n2;
}
res.setText(msg);
}
}
class MyDialog extends Dialog
{
MyDialog(Frame f, String s, Exception e)
{
super(f,s,false);
setVisible(true);
setSize(500,500);
setForeground(Color.blue);
setFont(new Font("Arial",Font.BOLD,15));
setLayout(null);
Label l=new Label(e.toString());
l.setBounds(20,100,500,30);
add(l);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
}
}
}
Post A Comment:
0 comments: