我正在尝试为班级创建一个小程序。
我应该处理两个可能的用户输入错误。我已经用 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);
}
}
}