我在处理项目中收到 java.lang 空指针异常,我认为它与 cDistance 有关,但我不太确定。我已经移动了一些东西,但仍然收到此错误。如果有人知道我哪里出错了,我将不胜感激。
class Ball {
int xpos, ypos;
int ballDiam;
color myColor;
boolean visible = true;
Ball(int tempdiam, color tempColor) {
ballDiam=tempdiam;
myColor=tempColor;
}
void update() {
if (visible) {
fill(myColor);
ellipse(xpos, ypos, ballDiam, ballDiam);
}
}
}
Ball hole, gball;//declare a ball object for the golfball and the hole
float cDistance = dist(gball.xpos, gball.ypos, hole.xpos, hole.ypos);
int click;//to keep track of clicks
String msg;
int steps = 20;
int difx, dify;
Boolean moving = false;
void setup() {
msg="";
click=0;
size(800, 400);
hole= new Ball(50, #000000);//making the
gball = new Ball(35, #ffffff);
}
void draw() {
background(#009900);
println("the click count is "+click);
//set the hole ball as a golf hole right in the middle of the green
hole.xpos = width/2;
hole.ypos = height/2;
hole.update();
if (click==0) {
//when no click has happened make the gball ball follow the mouse,
//after the click the ball will stay at the last position
gball.xpos=mouseX;
gball.ypos=mouseY;
msg="please place the golf ball";
}
else if (click==1) {//prompt the user to click again to shoot
msg="now click again to shoot";
difx = gball.xpos-hole.xpos;
dify = gball.ypos-hole.ypos;
}
else if (click==2) {
cDistance = dist(gball.xpos, gball.ypos, hole.xpos, hole.ypos);
if (cDistance>hole.ballDiam/2) {
moving = true;
gball.xpos-=difx/steps;
gball.ypos-=dify/steps;
gball.xpos+=5;
}
else {
moving = false;
gball.visible=false;
click=3;
}
}
gball.update();
textSize(20);
text(msg, 0, height-5);
}
void mouseClicked() {
if (!moving) {
click++;
}
}
堆栈跟踪:
java.lang.RuntimeException: java.lang.NullPointerException
at processing.core.PApplet.runSketch(PApplet.java:10573)
at processing.core.PApplet.main(PApplet.java:10377)
Caused by: java.lang.NullPointerException
at sketch_140421a.<init>(sketch_140421a.java:37)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at java.lang.Class.newInstance(Class.java:374)
at processing.core.PApplet.runSketch(PApplet.java:10571)
... 1 more
最佳答案
Ball#update() 调用 Ball#eclipse(),该函数尚未声明,因此为 null。 您还声明了 Hole 和 gball 类型为 Ball,但从未将它们初始化为 new Ball()。 我建议您使用 IDE,例如 Eclipse 或 IntelliJ,它们使诸如此类的小错误更容易消除。另外,下次发布堆栈跟踪。
关于java - 在处理中收到 java.lang nullpointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23202827/