问答题
下列程序是整数除法计算的程序,要求在出现异常时,能抛出异常信息。
考虑两种异常:
(1)输入非数字除数
(2)输入除法分母为零
该程序运行的三种结果状态如下:
(1)输入两个合法整数
(2)输入非数字除数
(3)输入除数为零
请将程序填写完整。
注意:不改动程序结构,不得增行或删行。
import java.awt.event.*;
public class ex3 extends ______implements ActionListener
private JTextField input1,input2, output;
private int number1,number2;
private double result;
public ex3()
______("示范异常");
Container c=getContentPane();
c.setLayout(new GridLayout(3,2));
c.add(new JLabe1("输入分子",SwingConstants.RIGHT));
input1=new JTextField(8);
c.add(input1);
c.add(new JLabe1("输入分母和回车",SwingConstants.RIGHT));
input2=new JTextField(8);
c.add(input2);
input2.addActionListener(this);
c.add(new JLabe1(”计算结果”,SwingConstants.RIGHT));
output=new JTextField();
c.add(output);
setSize(400,100);
show();
public void actionPerformed(ActionEvent e)
DecimalFormat precision3=new DecimalFormat("0.000");
output.setText("");//空的JTextField输出
try
number1=Integer.parseInt(input1.getText());
number2=Integer.parseInt(input2.getText());
result=quotient(number1,number2);
______;
catch (NumberFormatException nfe)
______(this,"你必须输入两个整数","非法数字格式",
JOptionPane.ERROR_MESSAGE);
catch (Exception dbz)
______(this,"除法异常","除数为零",
JOptionPane.ERROR_MESSAGE);
//定义求商的方法,如遇除数为零时,能抛出异常。
public double quotient(int numerator,int denominator)
throws Exception
if(denominator= =0)
throw new Exception();
return(double) numerator/denominator;
public static void main(String args[])
Java3 app=new Java3();
app.addWindowListener(
new WindowAdapter()
public void windowClosing(WindowEvent e)
e.getWindow().dispose();
System.exit(0);
);
【参考答案】
JFrame
Super
output.setText(precision3.format(resu......
(↓↓↓ 点击下方‘点击查看答案’看完整答案、解析 ↓↓↓)