在Java对话中没有捕获到空指针异常

时间:2011-05-30 01:17:37

标签: java exception try-catch

我正在尝试从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 个答案:

答案 0 :(得分:2)

你没有像你一样“抓住”NPE。从用户获取String,查看它是否== 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.

此处无需尝试/捕获。

另一种解决方法是让你的Player构造函数接受一个null String并将其更改为默认值:

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

答案 1 :(得分:2)

中添加无效值之前,最好先检查无效值的名称
String name = JOptionPane.showInputDialog("Please enter your name");
if(name == null || name.equals(""))name = DEFAULTNAME;
person = new Player(name,0);