I am currently coding the game of Snake for my computer science class. However, I ran into a lot of difficulties (since I am the only one in my block that is working alone) and I had to restart.
Right now I am just trying to make an array of objects (named Snake) from the second class (Segment) I made.
I get a NullPointerException on line 26: g.fillRect(xValue, yValue, size, size);
Where should I get an instance of Graphics to call this method on?
import java.awt.*;
import java.applet.*;
public class Segment extends Applet
{
private Graphics g;
private int xValue;
private int yValue;
private int size;
public Segment () {}
public Segment(int x, int y)
{
xValue = x;
yValue = y;
size = 10;
drawSegment(g);
}
public void drawSegment(Graphics g)
{
g.fillRect(xValue, yValue, size, size);
}
}
import java.awt.*;
import java.applet.*;
public class SnakeGame extends Applet
{
private Segment[] snake;
private Graphics g;
private int length;
private int sxValue;
private int syValue;
public SnakeGame()
{
length = 6;
snake = new Segment[length];
sxValue = 100;
syValue = 100;
for (int c = 0; c < snake.length; c++)
{
snake[c] = new Segment(sxValue, syValue);
sxValue = sxValue + 10;
}
drawSnake(g);
}
public void drawSnake(Graphics g)
{
for(int counter = 0; counter < length; counter++)
{
snake[counter].drawSegment(g);
}
}
}
However, I keep getting errors such as
java.lang.NullPointerException
at Segment.drawSegment(Segment.java:26)
at Segment.<init>(Segment.java:21)
at SnakeGame.<init>(SnakeGame.java:22)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at java.lang.Class.newInstance(Class.java:433)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:799)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:728)
at sun.applet.AppletPanel.run(AppletPanel.java:378)
at java.lang.Thread.run(Thread.java:745)