【问题标题】:Null pointer in an intersecting method with arrays (java)与数组相交的方法中的空指针(java)
【发布时间】:2014-09-19 01:32:11
【问题描述】:
Exception in thread "Thread-1" java.lang.NullPointerException
    at java.awt.Rectangle.intersects(Rectangle.java:786)
    at Robotron.intersecting(Robotron.java:182)
    at Robotron.run(Robotron.java:349)
    at java.lang.Thread.run(Thread.java:745)

麻烦就在这里:

public void intersecting(Sprite r1, Sprite r2)
{
    System.out.println("The grunts isAlive is: "+r1.isAlive+" his xpos is: "+r1.rec.x+" his ypos is: "+r1.rec.y);
    if(r1.rec.intersects(r2.rec) && r1.isAlive==true && r2.isAlive==true)
    {
        r1.isAlive=false;
        r2.isAlive=false;
    }
}

我的 System.out 的输出是:The grunts isAlive is: true his xpos is: 936 his ypos is: 478。但由于某种原因,它给了我一个空指针

这就是我初始化 Grunts 的方式,也许问题出在那儿?

for(int i=0; i<grunt.length;i++)
{
    int randX = (int)(Math.random()*worldx);
    int randY = (int)(Math.random()*worldy);
    if(hero.outerCircle.inCircle(randX,randY)!=true)
    {
        grunt[i] = new EnemyD4(randX,randY, worldx, worldy, 50,70);
    }
    if(hero.outerCircle.inCircle(randX,randY)==true)
    {
        randX+=100;
        grunt[i] = new EnemyD4(randX,randY, worldx, worldy, 50,70);
    }
}

【问题讨论】:

  • 你怎么打电话给intersecting()
  • 空指针异常发生在哪里?
  • 一个可能的原因是线程和主程序是分开执行的。但是,再次向我们展示完整(注释)代码以了解问题。

标签: java arrays nullpointerexception rectangles intersect


【解决方案1】:

在这种情况下,只需遵循堆栈跟踪!我从中猜测空指针是在这里抛出的:

if(r1.rec.intersects(r2.rec) && r1.isAlive==true && r2.isAlive==true)

确切地说,它是在这里抛出的 r1.rec.intersects(r2.rec)(假设 r1.recr2.rec 不为空)。

如果您检查 awt 包中 Rectangle#intersects(Rectangle r) 的代码,您将在第 786 行看到:

int rw = r.width;

这就是 NPE 发生的地方。 r 这是你的r2.rec,这意味着它是空的。您要么需要在调用 intersects() 之前检查这种情况,要么需要修复调用 intersecting(Sprite r1, Sprite r2) 的方式。

【讨论】:

    【解决方案2】:

    我认为您对 intersects 的输入为空。检查 if 条件时,请先检查 r1 和 r2:

    if(r1.isAlive==true && r2.isAlive==true && r1.rec.intersects(r2.rec)) {
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-21
      • 1970-01-01
      • 2013-09-07
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2017-05-02
      相关资源
      最近更新 更多