简体   繁体   中英

Null Pointer Exception in Java. (Broken for loop with array?)

So I've read a bunch of other questions by other people but couldn't find a solution to this issue that works for me. I'm learning java and decided to make a simple console based Battleship game to test some basic java principle and implementation. Right at the very beginning of the program, I get a NullPointerException error.

Here's what my code looks like up to the point of the error:

public class Battleship {

public static String[] xValues = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
public static String[] shipNames = {"patrol", "sub", "cruiser", "battle", "carrier"};
public static boolean isCollision = true;

//Create the Ship Array
public static Ship[] ships = new Ship[5];



public static void main(String[] args) {

    //Welcome the User
    System.out.println("Welcome to Battleship!\nLet's see how many tries it take to sink the ships!");

    //Now, let's make 5 kinds of ships: Patrol Boat, Submarine, Cruiser, Battleship, Carrier. Each has a different size.
    for (int i = 0; i < shipNames.length; i++){
        ships[i].setName(shipNames[i]);
    }

The only thing I could think of was perhaps encapsulation issues because the static values for array shipNames is outside of the main method. But placing it inside the main method doesn't fix it either. I thought perhaps garbage collection happened at the initiation of the main method and destroyed the array because it was empty, but that doesn't work either because the debugger shows the shipNames.length = 5 I'm plum confused. Any ideas here? Thanks in advance.

You need to create a new Ship object for each slot of the array. Remember that the default value for an object is null .

for (int i = 0; i < shipNames.length; i++){
        ships[i] = new Ship();
        ships[i].setName(shipNames[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM