[英]Null Pointer Exception not caught in java dialogue
I'm trying to receive input from a java dialog and I can't seem to catch the NullPointerException
when the box is closed, can anyone help?我正在尝试从 java 对话框接收输入,并且在关闭框时我似乎无法捕获NullPointerException
,有人可以帮忙吗?
private static final String DEFAULTNAME = "Player001";
public class Player implements Serializable
{
private String name;
private int score;
public Player(String Pname,int Pscore)
{
name = Pname;
score = Pscore;
}
}
try
{
person = new Player(JOptionPane.showInputDialog("Please enter your name"),0);
}
catch(NullPointerException e)
{
person = new Player(DEFAULTNAME,0);
}
catch(Throwable t)
{
person = new Player(DEFAULTNAME,0);
}
Does anyone have a solution or is there a way of making the dialog unable to close?有没有人有解决方案或者有没有办法让对话框无法关闭?
You don't "catch" a NPE like you're doing.你不会像你正在做的那样“抓住”一个 NPE。 Get the String from the user, see if it == null, and then if so use the default player name.从用户那里获取String,看是否== null,如果是则使用默认播放器名称。 In pseudo code:在伪代码中:
call JOptionPane and get player name
If player name is null
create new Player with default name
else
create new Player with the user-entered name.
No need for try/catch here.这里不需要尝试/捕获。
Another way to solve it is to let your Player constructor accept a null String and change it to default:另一种解决方法是让您的 Player 构造函数接受 null 字符串并将其更改为默认值:
public Player(String Pname,int Pscore)
{
name = (Pname == null || Pname.trim().isEmpty()) ? DEFAULT_NAME : Pname;
score = Pscore;
}
you are better off checking the name for invalid values before adding it in您最好在添加之前检查名称中的无效值
String name = JOptionPane.showInputDialog("Please enter your name");
if(name == null || name.equals(""))name = DEFAULTNAME;
person = new Player(name,0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.