简体   繁体   English

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

[英]NullPointerException on array with length one initializing

This is my method to updateHighScoreRecords() : 这是我的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;
}

And this is my GameRecord class: 这是我的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;
}
}

But there is a nullPointer exception on this line: 但是这一行有一个nullPointer异常:

gameRecord[0].setName(name);

Why? 为什么?

I want to return an array of GameRecord type when highScoreRecords length is zero. highScoreRecords长度为零时,我想返回一个GameRecord类型的数组。

You never initialized zeroth element. 您从未初始化第零个元素。 First you have to add element at zero position and then access it. 首先,您必须在零位置添加元素,然后访问它。

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

When you wrote 当你写

  gameRecord = new GameRecord[1];

That means you are just initializing an array to store 2 GameRecord elements. 这意味着您只是初始化一个数组来存储2个GameRecord元素。 Nothing else. 没有其他的。 Initially those are null 's. 最初,这些是null You need to initialize each element to use them further. 您需要初始化每个元素以进一步使用它们。 Otherwise they are still null. 否则,它们仍然为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM