作业异常处理问题

时间:2012-07-11 00:32:31

标签: java applet try-catch

我正在尝试为课程创建一个小程序。

我应该处理两个可能的用户输入错误。我用if / else语句用零处理了除法。

然而。我试图处理异常,如果用户试图将字母或符号放入文本框而不是数字....但我的catch语句将不会发现问题。相反,它通过0 else语句来实现除法。如果可以提供帮助,请查看并告诉我

 /*
 * Curtis Sizemore
 * IT 259 - Intermediate Java
 * Unit 8
 * Working with Applets
 * I attest that this is a product of my own creation.
 * 
 */
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
 *
 * @author Curtis
 */
public class JDivide extends JApplet implements ActionListener
{
JTextField numer = new JTextField(5);
JTextField denom = new JTextField(5);
JLabel intro = new JLabel("Please enter two numbers.");
JLabel num = new JLabel("Numerator: ");
JLabel den = new JLabel("Denominator: ");
JLabel result = new JLabel();
JButton solve = new JButton("Click Me to Solve!");
Container con = getContentPane();
double numerator;
double denominator;
 double quotient;
 String n;
String d;
 String q;


@Override
public void init()
{
    con.setLayout(new FlowLayout());
    con.add(intro);
    con.add(num);
    con.add(numer);
    con.add(den);
    con.add(denom);
    con.add(solve);
    con.add(result);
    solve.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) 
{



      n = numer.getText();
      d = denom.getText();
    try
      {
      double numerator = Double.parseDouble(n);
    double denominator = Double.parseDouble(d);
      }
      catch(NumberFormatException x)
      {
      result.setText("Numbers Only Please.");
      }


      if(denominator==0)
      {
      result.setText("Division by 0 is undefined.");
      }
      else
      {
      double quotient = numerator/denominator;
      q = Double.toString(quotient);
      result.setText(q);
}
 }

}

1 个答案:

答案 0 :(得分:2)

您需要将其余代码放在try块中,或者抛出异常。否则,即使输入了非数字,该方法仍将尝试计算商。