【问题标题】:Java "foreach" not working...nullPointerExceptionJava“foreach”不起作用...nullPointerException
【发布时间】:2013-11-23 16:56:40
【问题描述】:
Point bl = new Point(Guy.x, Guy.y + Guy.height);
Point br = new Point(Guy.x + Guy.width, Guy.y + Guy.height);

for(Tile p: platforms){
            if (p.y == br.y && br.x >= p.x && bl.x <= p.x + p.width) {
                isOnPlatform = true;
            }else{
                isOnPlatform = false;
            }

   }

当我运行那段代码时,控制台显示“NullPointerException”。为什么这不起作用?

我已经定义/初始化了变量Tile[] platforms。另外,当我运行它时,Guy 并没有掉下来。

另外,当我这样做时,它会起作用:

//for(Tile p: platforms){
    if (platforms[1].y  == br.y && br.x >= platforms[1].x && bl.x <= platforms[1].x + platforms[1].width) {
                isOnPlatform = true;
            }else{
                isOnPlatform = false;
            }

 //  }

但是,我还有另外 2 个 platforms,我会再添加 20 个。我不想对每个platforms 都这样做。

有什么想法吗?

【问题讨论】:

  • 什么是“NullPointerException”...至少要努力一下。
  • NullPointerException 发生在哪里(行号)?您可以在堆栈跟踪中看到它。
  • 检查您的平台[0] 元素
  • 将鼠标悬停在您添加到问题中的 nullpointerexception 标签上。然后在出现的弹出窗口中单击“信息”。或者使用谷歌。

标签: java arrays foreach nullpointerexception collision-detection


【解决方案1】:

foreach 循环遍历所有元素(包括 null),因此如果您有长度为的平台数组,例如10,并且只有 2 个元素,那么 p.y 将导致 NPE(空指针异常),因为当 index == 2 时 p 为空。您必须更改代码以避免在空元素上循环:

for (Tile p : platforms) {
  if (p == null) {
    continue; // or break, whatever is better in your case
  }
  if (p.y == br.y && br.x >= p.x && bl.x <= p.x + p.width) {
    // ...
  }
}

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 2018-08-22
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多