This site requires JavaScript, please enable it in your browser!
Greenfoot back
mr_alex
mr_alex wrote ...

2021/10/20

NullPointerException and I don't know why

mr_alex mr_alex

2021/10/20

#
Hi everyone, I have a question: I have the following class:
import greenfoot.*;
public class Ground extends Actor
{
    private int y = this.getWorld().getHeight() - this.getImage().getHeight() / 2;
}
and it throws this exception:
 java.lang.NullPointerException
	at Ground.<init>(Ground.java:4)
	at MyWorld.<init>(MyWorld.java:11)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
	at greenfoot.core.Simulation.newInstance(Simulation.java:580)
	at greenfoot.platforms.ide.WorldHandlerDelegateIDE.lambda$instantiateNewWorld$0(WorldHandlerDelegateIDE.java:143)
	at greenfoot.core.Simulation.runQueuedTasks(Simulation.java:470)
	at greenfoot.core.Simulation.maybePause(Simulation.java:299)
	at greenfoot.core.Simulation.runContent(Simulation.java:190)
	at greenfoot.core.Simulation.run(Simulation.java:183)
I don't know what's wrong. The error must be in this Part of the code:
this.getWorld().getHeight()
because when I replace it with a number like 800 everything works
danpost danpost

2021/10/20

#
mr_alex wrote...
it throws this exception:
 java.lang.NullPointerException
The error must be in this Part of the code:
this.getWorld().getHeight()
Correct. The getWorld method returns the world the actor is currently in. However, the actor is not in any world while it is being created (initiated). Fields with declared values are assigned during creation and the constructor is executed during creation. During that time getWorld will return a null value. You could override the Actor class instant method addedToWorld(World) to perform any final initiation of your actor that needs done involving the world it is placed into.
mr_alex mr_alex

2021/10/20

#
danpost wrote...
mr_alex wrote...
it throws this exception:
 java.lang.NullPointerException
The error must be in this Part of the code:
this.getWorld().getHeight()
Correct. The getWorld method returns the world the actor is currently in. However, the actor is not in any world while it is being created (initiated). Fields with declared values are assigned during creation and the constructor is executed during creation. During that time getWorld will return a null value. You could override the Actor class instant method addedToWorld(World) to perform any final initiation of your actor that needs done involving the world it is placed into.
Thanks!
You need to login to post a reply.