gpt4 book ai didi

java - 数组相交方法中的空指针(java)

转载 作者:行者123 更新时间:2023-12-01 22:42:32 25 4
gpt4 key购买 nike

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

最佳答案

在这种情况下,只需跟踪堆栈跟踪即可!我猜测这里抛出了空指针:

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) 的方式。

关于java - 数组相交方法中的空指针(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25924997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com