Eclipse suggests Null Pointer exception, though I believe I initialized my object

不想你离开。 提交于 2019-12-29 09:14:22

问题


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

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?

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

回答1:


The line:

GOval bowl = new GOval(10,10);

is declaring a new GOval and hiding the global GOval defined at the bottom.

That line should just be:

bowl = new GOval(10,10);



回答2:


You are shadowing your bowl field at the class level in the init method,

private GOval bowl; 

public void init() {
  // GOval bowl = new GOval(10,10);
  bowl = new GOval(10,10);
  add(bowl);
  addMouseListeners();
}



回答3:


Like most people already mentioned you are shadowing your bowl variable.

GOval bowl = new GOval(10,10);

should be replaced with

bowl = new GOval(10,10);

You can configure eclipse that he gives you a warning when you are doing this. In the preferences you have a dedicated part for this under java -> compiler -> errors/warnings



来源:https://stackoverflow.com/questions/24698684/eclipse-suggests-null-pointer-exception-though-i-believe-i-initialized-my-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!