使用构造函数将变量放入对象会抛出java.lang.NullPointerException

时间:2014-04-23 16:40:00

标签: java arrays

使用此代码

System.out.println("New Mark Entry\n--------------" + "\n\nEnter the description (up to 40 characters will be displayed):");
name = TextIO.getlnString();
if (name.length() > 40) {
    name = name.substring(0,40);
}
System.out.println("What was the assignment out of?");
totalMark = TextIO.getlnDouble();
System.out.println("What was the students mark?");
mark = TextIO.getlnDouble();
System.out.println("What was the weight of this assignement?");
weight = TextIO.getlnDouble();
input = 1;
int openSpot = 0;
for(int i = 0; i < markbook.length; i++) {
    if(markbook[i].getAssignment(name) == null) {   // java.lang.NullPointerException is thrown here
        openSpot = i;
        break;
    }

}
markbook[openSpot] = new Mark(name, totalMark, mark, weight);
break;

导致抛出java.lang.NullPointerException。我有点困惑如何解决这个问题。如果有人可以帮助或指出我正确的方向,那将是非常有用的

3 个答案:

答案 0 :(得分:0)

如果NPE发生在该确切的行上,最可能的原因是markbook[i]null。您没有显示您是如何初始化它的,但除了分配数组外,您还需要创建元素。

有关示例,请参阅https://stackoverflow.com/a/10044418/367273

答案 1 :(得分:0)

我会查看已抛出NullPointerException的行。

让它说是

markbook[i].getAssignment(name)

然后我会检查我确实将markbook [i]设置为某个东西,否则它将为null。

注意:这还不够。

MyType[] markbook = new MyType[4];

因为这与

相同
MyType[] markbook = { null, null, null, null };

如果它仍然没有意义,我会使用调试器调试你的代码。

答案 2 :(得分:0)

您正在初始化markbook并尝试在

之前使用它
for(int i = 0; i < markbook.length; i++) {
        if(markbook[i].getAssignment(name) == null) {   // java.lang.NullPointerException is thrown here
            openSpot = i;
            break;
        }

    }
    markbook[openSpot] = new Mark(name, totalMark, mark, weight);//you are initializing markbook after and trying to use it before

应该如下

//initialize first
markbook[openSpot] = new Mark(name, totalMark, mark, weight);

//use later
for(int i = 0; i < markbook.length; i++) {
        if(markbook[i].getAssignment(name) == null) {   // java.lang.NullPointerException is thrown here
            openSpot = i;
            break;
        }

    }