【问题标题】:Using a constructor to put variables into an object throws java.lang.NullPointerException使用构造函数将变量放入对象会引发 java.lang.NullPointerException
【发布时间】:2014-04-23 16:39:59
【问题描述】:

使用此代码

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。我对如何解决这个问题感到有点困惑。如果有人可以帮助或指出我正确的方向,将不胜感激

【问题讨论】:

  • 您检查过markbook[i] 中的内容吗?
  • 堆栈跟踪通常会有所帮助。
  • 在此代码中放置断点..即name,markbook[i] 或类似的案例...
  • 你初始化markbook[]了吗?

标签: java arrays


【解决方案1】:

您正在初始化标记簿并尝试在之前使用它

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;
        }

    }

【讨论】:

    【解决方案2】:

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

    例如,见https://stackoverflow.com/a/10044418/367273

    【讨论】:

      【解决方案3】:

      我会查看抛出 NullPointerException 的行。

      假设是

      markbook[i].getAssignment(name)
      

      然后我会检查我是否真的将 markbook[i] 设置为某个值,否则它将为空。

      注意:这还不够。

      MyType[] markbook = new MyType[4];
      

      因为这是一样的

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

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

      【讨论】:

        猜你喜欢
        • 2013-05-13
        • 2012-01-07
        • 1970-01-01
        • 2016-04-11
        • 1970-01-01
        • 2016-02-15
        • 1970-01-01
        • 1970-01-01
        • 2020-04-30
        相关资源
        最近更新 更多