有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

是否有人有解决方案,或者是否有办法使对话框无法关闭


共 (2) 个答案

  1. # 1 楼答案

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

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

    你不会像现在这样“抓住”NPE。从用户那里获取字符串,查看它是否==null,如果是,则使用默认的播放器名称。在伪代码中:

    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.
    

    这里不需要尝试/捕捉

    另一种解决方法是让玩家构造函数接受空字符串并将其更改为默认值:

    public Player(String Pname,int Pscore)
    {
         name = (Pname == null || Pname.trim().isEmpty()) ? DEFAULT_NAME : Pname;
         score = Pscore;
    }