gpt4 book ai didi

java - java对话中未捕获空指针异常

转载 作者:行者123 更新时间:2023-12-01 19:17:01 24 4
gpt4 key购买 nike

我正在尝试从 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);
}

有人有解决方案或者有办法使对话框无法关闭吗?

最佳答案

在添加名称之前,最好先检查名称是否存在无效值

String name = JOptionPane.showInputDialog("Please enter your name");
if(name == null || name.equals(""))name = DEFAULTNAME;
person = new Player(name,0);

关于java - java对话中未捕获空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com