在我的处理项目中,我收到了一个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发布于 2014-04-21 18:10:48
您的球是声明的,但从未在这里初始化:
Ball hole, gball;//declare a ball object for the golfball and the hole
float cDistance = dist(gball.xpos, gball.ypos, hole.xpos, hole.ypos);==> NPE
您应该首先使用一些值初始化Balls,如下所示:
gball = new Ball();
hole = new Ball();实际上,您可能希望为Ball设置一个构造函数,该构造函数还可以将一些值设置为xpos / ypos,或者只是设置一些默认值,例如:
class Ball {
int xpos = 0;
int ypos = 0;
//...发布于 2014-04-21 18:12:07
Ball#update()调用未声明的Ball#eclipse(),因此为null。您还声明洞和球类型的球,但从来没有初始化到新的球()。我建议您使用像Eclipse或IntelliJ这样的IDE,它们会使这样的小bug更容易清除。另外,下次发布堆栈跟踪。
https://stackoverflow.com/questions/23202827
复制相似问题