我必须在学校创建一个计算器应用程序并且计算器工作正常,但是现在我必须创建一个异常,当用户输入字符串而不是整数值时,它会显示用户友好的消息。
这是我现在使用JFrame和所有内容的代码:
private void minActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef - invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
private void plusActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef + invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
private void keerActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef * invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
private void delenActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef / invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
此代码包含所有事件及其执行的操作(第一个用于减法等...)。我使用Netbeans作为我的开发环境,我尝试添加try和catch语句,如下所示:
try {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef - invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
catch(/* what do I put here? */) {
// what do I do here?
}
所以我的问题是,如何在用户输入的值不是正确的返回类型时创建异常(必需:Integer,found:String)。
双打或其他返回类型目前并不重要,只有字符串。
提前致谢!
答案 0 :(得分:2)
使用 NumberFormatException 。当将String转换为数字的方法接收到无法转换的String时,抛出此异常。像Integer.parseInt(“sadfasd”);
答案 1 :(得分:2)
您可以将NumberFormatException javaDoc或Exception e用于一般异常,然后打印如下消息:
catch (NumberFormatException e) {
System.out.println("Invalid entry, please enter a number");
}
答案 2 :(得分:2)
要在输入字符串时捕获(空白文本也计算在内),请使用NumberFormatException:
catch (NumberFormatException n) {
System.out.println("Please enter a number.");
}
要捕获任何错误,请使用Exception:
catch (Exception e) {
System.out.println("Error.");
}
您可以将这些组合起来以捕获不同的错误,以便您可以单独处理它们。例如:
try
{
String s = "hi";
int i = Integer.parseInt(s); // will go into NumberFormatException n
s = s.substring(-2); // will go into Exception e
}
catch (NumberFormatException n) {
System.out.println("Please enter a number.");
}
catch (Exception e) {
System.out.println("Unspecified error (not a NumberFormatException).");
}