Eclipse 建议空指针异常,但我相信我初始化了我的对象 [英] Eclipse suggests Null Pointer exception, though I believe I initialized my object
问题描述
正如标题所说,我有 NPE 错误.它在线上发生:
As the title says I have NPE error. It happens on line:
while (getWidth() > bowl.getX()+10) {
如果我删除它,它会显示它发生在下一行:
If I remove it, it shows it happens on next line:
bowl.move(10.0, 0);
我得出的结论是 eclipse 没有看到我的碗"被初始化.为什么?新 GOval"不处理这个吗?我在这里的一个线程中看到一个解决方案是将声明和初始化拆分为不同的行,但我认为这不太可能是主要解决方案(此外,它对我的情况没有帮助)对此有任何建议代码?
I concluded that eclipse does not see my "bowl" initialized. Why? Doesn't "new GOval" deal with that? I've seen in one of the threads here that a solution was to split declaration and initialization to different lines, but I think it is unlikely to be a primary solution (besides, it didn't help in my case) Any suggestions on this code?
这段代码应该是创建一个圆圈,把它放在屏幕的左上角,点击鼠标按钮后移动圆圈.圆圈绘制成功,但点击后出现NPE消息.
This code is supposed to create a circle, put it in the left-upper corner of the screen, and move the circle after mouse-button is clicked. The circle is drawn successfully, but the NPE message shows up after the click.
import acm.program.*;
import acm.graphics.*;
import java.awt.event.*;
public class animation extends GraphicsProgram {
public void init() {
GOval bowl = new GOval(10,10);
add(bowl);
addMouseListeners();
}
public void mouseClicked(MouseEvent e) {
while (getWidth() > bowl.getX()+10) {
bowl.move(10.0, 0);
pause(50);
}
}
private GOval bowl;
}
推荐答案
行:
GOval bowl = new GOval(10,10);
正在声明一个新的 GOval 并隐藏在底部定义的全局 GOval.
is declaring a new GOval and hiding the global GOval defined at the bottom.
那行应该是:
bowl = new GOval(10,10);
这篇关于Eclipse 建议空指针异常,但我相信我初始化了我的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!