我正在写一个Java程序,我得到了一些文本框和一个按钮。对于输入字符串:“”当填写textfields
即使我在运行程序时填写了所有文本字段,我也会得到一个java.lang.NumberFormatException: For input string: ""
。
我的代码看起来是这样的:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
method();
}
}
);
public void method() {
try {
String string1 = textfield1.getText();
String string2 = textfield2.getText();
String string3 = textfield3.getText();
if (string1.length() == 0 || string2.length() == 0 || string3.length() == 0) {
System.out.println("fill in the required text fields");
return;
}
int number = Integer.parseInt(textfield3.getText());
//do something
}
catch (NumberFormatException e) {
System.out.println("Wrong format");
}
}
编辑:
将'textfield3.getText();'分配给'string3'。不妨使用它!另外,调试你的代码。它会告诉你你错在哪里。在看过你提供的代码后,我看不到任何错误。现在是消除一些愚蠢错误的时候了。你确定'textfield3'是正确的字段吗? – christopher 2013-05-09 21:52:44
我的猜测是你的代码看起来像这样,但不完全。而这个错误可能是在“不完全”的部分。张贴重现问题的SSCCE。 – 2013-05-09 21:55:25
尝试使用String#trim().length()。添加一些System.outs来测试文本字段的值,并尝试调试代码 – MadProgrammer 2013-05-09 22:05:34