问题
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