数组的NullPointerException,长度为1初始化

时间:2014-08-07 12:59:41

标签: java arrays

这是updateHighScoreRecords()的方法:

    public GameRecord[] updateHighScoreRecords(GameRecord[] highScoreRecords, String name, int level, int score) {
    GameRecord[] gameRecord = null;

    if (highScoreRecords.length == 0) {     // Rule one
        gameRecord = new GameRecord[1];
        gameRecord[0].setName(name);
        gameRecord[0].setLevel(level);
        gameRecord[0].setScore(score);
        System.out.println("Role one Done");
    }
    return gameRecord;
}

这是我的GameRecord课程:

public class GameRecord {
private String name;
private int level;
private int score;

public GameRecord(String name, int level, int score) {

    this.name = name;
    this.level = level;
    this.score = score;
}
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
public int getLevel() {
    return level;
}
public void setLevel(int level) {
    this.level = level;
}

public int getScore() {
    return score;
}

public void setScore(int score) {
    this.score = score;
}
}

但是这一行有一个nullPointer异常:

gameRecord[0].setName(name);

为什么?

我想在GameRecord长度为零时返回highScoreRecords类型的数组。

1 个答案:

答案 0 :(得分:4)

您从未初始化第0个元素。首先,您必须在零位置添加元素,然后访问它。

 gameRecord[0] = new GameRecord();
 gameRecord[0].setName(name);

当你写

  gameRecord = new GameRecord[1];

这意味着您只是初始化一个数组来存储2个GameRecord元素。没有其他的。最初这些是null。您需要初始化每个元素以进一步使用它们。否则它们仍为空。