![](/img/trans.png)
[英]Exception in thread “main” java.lang.NumberFormatException: For input string: “” in Java
[英]java - Exception in thread “main” java.lang.NumberFormatException: For input string: “” at
我试图运行以下示例,如果我在整数框/字段中输入字母或选择“确定/取消”而不输入值,则会退出确定或强制您输入有效的数字值。
对于文本字段,它可以正常工作,但不能用于整数,但出现以下错误。
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
for this code, is it possible to achieve what I want? thanks for any answers in advance
import javax.swing.*;
public class Methods
{
public static void main(String[] args)
{
//THIS IS FOR THE 1ST POP UP BOX
// prompt the user to enter their name
String name = JOptionPane.showInputDialog( "What is your Firstname?");
// get the user's input. note that if they press Cancel, 'name' will be
null
System.out.printf("The user's name is '%s'.\n", name);
//
//THIS IS FOR THE 2ND POP UP BOX
// prompt the user to enter their name
String nametwo = JOptionPane.showInputDialog(frametwo, "What is your
Surname?");
// get the user's input. note that if they press Cancel, 'name' will be
null
System.out.printf("The user's name is '%s'.\n", nametwo);
//
//THIS IS FOR THE 3RD POP UP BOX
// prompt the user to enter their age
int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree,
"How old are you?"));
//if (num.isEmpty())
// get the user's input. note that if they press Cancel, 'age' will be
null
System.out.printf("Your age is '%s'.\n", namethree);
System.out.println("********************************");
System.exit(0);
}
}
您需要在对Integer.parseInt的调用周围添加异常处理以捕获转换错误-此方法将为无法转换为Integer的任何字符串引发NumberFormatException。
就像是:
try
{
int namethree = Integer.parseInt(JOptionPane.showInputDialog(framethree,
"How old are you?"));
}
catch (NumberFormatException)
{
//TODO: display an error message and retry the input
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.