Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java NullPointerException

I seem to keep getting the same Exception in my code and I can seem to figure out why ..

public class BattleShip {

public static void main(String[] args) {

System.out.println("Hello World");
Game game = new Game();
Prompter prompter = new Prompter(game);
game.createMap(5);
game.createBattleShips();
prompter.promptForGuess();
game.getxCo();  

}

}

import java.util.ArrayList;

import java.util.Random;

public class Game {

private int mapSize;

private String hits;

private String misses;

ArrayList map = new ArrayList();

public final int NUMBER_OF_SHIPS = 3;

private int[] cooX;

private int[] cooY;

ArrayList guesses = new ArrayList();

private static final int MAX_TRIES = 10;

public void createBattleShipX() {

Random rand = new Random();

int x = 0;

while (x < NUMBER_OF_SHIPS) {

  x++;

  cooX[x] = rand.nextInt(5);

}

}

public void createBattleShipY() {

Random rand = new Random();

int x = 0;

while (x < NUMBER_OF_SHIPS) {

  x++;

  cooY[x] = rand.nextInt(5);

}

}

}

Exception in thread "main" java.lang.NullPointerException
at Game.createBattleShipX(Game.java:94)
at Game.createBattleShips(Game.java:17)
at BattleShip.main(BattleShip.java:8)

I didn't add much of the code due to it not being recognized as 'code'. Thanks for taking the time to read this and help me.

1 Answer

Hello,

You haven't initialized the arrays:

Change:

public final int NUMBER_OF_SHIPS = 3;
private int[] cooX;
private int[] cooY;

By:

public static final int NUMBER_OF_SHIPS = 3;
private int[] cooX = new int[NUMBER_OF_SHIPS];
private int[] cooY = new int[NUMBER_OF_SHIPS];

Also you should increment x after using it:

Change:

x++;
cooX[x] = rand.nextInt(5);

By:

cooX[x] = rand.nextInt(5);
x++;

Regards