java.lang.NumberFormatException:对于输入字符串:"&引用;,而不是将字符串转换为数字
“单击“保存”按钮但未将字符串转换为数字时,会发生NumberFormatException错误。” 我试过:java.lang.NumberFormatException:对于输入字符串:"&引用;,而不是将字符串转换为数字,java,runtime-error,runtimeexception,Java,Runtime Error,Runtimeexception,“单击“保存”按钮但未将字符串转换为数字时,会发生NumberFormatException错误。” 我试过: try { result = Integer.parseInt(input); } catch(Exception e) { if(input == null || input.isEmpty()) { // case 1a return 0; //case 1a } 我想要“发送”按钮将数据发送到数据库。注意整数在-2147483648到+2147483647之间 如果您传递的
try {
result = Integer.parseInt(input);
} catch(Exception e) {
if(input == null || input.isEmpty()) { // case 1a
return 0; //case 1a
}
我想要“发送”按钮将数据发送到数据库。注意整数在-2147483648到+2147483647之间 如果您传递的是高于整数的任何内容或包含字符的字符串,则会得到该错误 案例1
Integer.parseInt("1232322132434")
错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1232322132434"
案例2:
Integer.parseInt("1232w")
Exception in thread "main" java.lang.NumberFormatException: For input string: "1232w"
因此,您尝试的应该是可行的,但看起来您在思考时一定没有调用它(可能是因为您没有想到valueOf调用parseInt)。您可以将其编写为一个小函数,如:
public static Integer safeValueOf(String s) {
Integer result = null; // signals error of unanticipated kind
try {
result = Integer.parseInt(s);
} catch (NumberFormatException e) {
if (s == null || s.isEmpty()) { // case 1a
result = 0; //case 1a
}
} finally {
return result;
}
然后替换像pst.setInt(4,Integer.valueOf(jTextField4.getText())这样的行代码>带有
pst.setInt(4, safeValueOf(jTextField4.getText()));
我将其添加到catch参数中
catch(HeadlessException | NumberFormatException | SQLException e)
另外,当我输入数据时,日期格式是错误的,所以我更改了它
最后,我删除了:
pst.setString(10, jTextField10.getText());
“我没有将字符串转换为数字”-您正在调用Integer.parseInt
和Integer.valueOf
,这两个函数都将字符串转换为数字…如果我将它们设置为字符串,这会带来错误。我该如何将整数值发送到数据库。很可能您的一个文本字段是空的-此时您想做什么?@JonSkeet,问题是,如果文本字段是空的,提问者希望将值设置为0——参见第一段代码中的案例1a。目前还不清楚该块何时被调用,因为如果它是为了防止出现空块,它应该可以工作。波尔,当你说你试过第一个街区时,你是在什么阶段试的?还要避免特殊角色。不要输入像32567这样的余额注意,在标题中,用户有传递空字符串的问题,可能是传递给parseInt。但不清楚的是,用户似乎也尝试过检查空字符串,这应该会有所帮助。我建议Pol应该使用e.printStackTrace()函数来反映问题的确切根源。带有错误的实际行
pst.setString(10, jTextField10.getText());