这可能是一种有点非常规的寻求帮助的方式,但我的代码遇到了空指针运行时错误,但运行时错误的范围太大,无法发布到 stackoverflow 上。我真的很想弄清楚这一点,所以我可以通过电子邮件向你们中的一个人发送我的代码以找出问题所在吗?我知道运行时错误会告诉它所触发的具体行号,但老实说,我无法弄清楚为什么会发生这种情况。非常感谢!!
堆栈跟踪:
java.lang.NullPointerException
at Maze.getNumRandOccupants(Maze.java:118)
at P4TestDriver.testMaze(P4TestDriver.java:995)
at P4TestDriver.main(P4TestDriver.java:116)
at __SHELL8.run(__SHELL8.java:7)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at bluej.runtime.ExecServer$3.run(ExecServer.java:814)
java.lang.NullPointerException
at Maze.addRandomOccupant(Maze.java:130)
at P4TestDriver.testMazeReadWrite(P4TestDriver.java:1071)
at P4TestDriver.main(P4TestDriver.java:127)
at __SHELL8.run(__SHELL8.java:7)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at bluej.runtime.ExecServer$3.run(ExecServer.java:814)
最佳答案
来自您的评论:
public int getNumRandOccupants() { return randOccupants.size(); }
因为它位于堆栈跟踪的顶部,所以这意味着调用此方法时 randOccupants
字段为 null。
此外,如果您在 addRandomOccupant
处获得另一个 NPE,则相同的集合也可能为 null。您可能只是忘记构建集合。
关于Java运行时错误: null pointer exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324264/