0

I'm trying to code a battleship game and im getting a weird error when i run it: Exception in thread "main" java.lang.NullPointerException at Caculations.findShip(Caculations.java:29) at Board.main(Board.java:60)

Please help im stuck and i dont know how to continue! Here is my code: (Note, its in 2 class files in my eclipse work enviorment)

public class Board {

    public static void main(String[] args) {

        boolean continuePlay = true;
        int[][] board = new int[10][10]; // creating 2d array 'board'
        char[][] boardGraphical = new char[10][10]; // creating 2d array 'board
                                                    // this time the visual
        for (int x = 0; x < 10; x++) { // for within for //initializing elements
                                        // in both boards using double for
                                        // method
            for (int y = 0; y < 10; y++) {
                board[x][y] = 0;
                boardGraphical[x][y] = 'o';
                System.out.println("Board element " + x + " " + y // printing
                                                                    // initialized
                                                                    // elements
                                                                    // here
                        + " initialized");
            }

        }

        /*
         * 1) Make user ships 1 and computer ships 2 (all numbers other than 0 =
         * true)
         * 
         * 2) Make it where if the computer gets a hit on a '1' than it sets
         * that value to like a 3 or something so it knows when the ship is
         * sunk. So in a if it does if([x][y] && [x][y])
         * System.out.println("You sunk my ship!");
         * 
         * 3) REMEMBER YOU CAN DO MULTIPLE IFS INSIDE IFS FOR MULTIPLE
         * CONDITIONS. 4) declare ships here!
         * 
         * 5) PUT STUFF IN A WHILE LOOP SO COMP CAN KEEP GOING
         */
        board[3][3] = 1; // declaring a battleship. Very important.
        board[3][4] = 1;
        board[3][5] = 1;
        boardGraphical[3][3] = 's';
        boardGraphical[3][4] = 's';
        boardGraphical[3][5] = 's';

        while (continuePlay == true) { // while loop so that computer keeps
                                        // guessing
            // WITHIN THIS LOOP KEEP REPRINTING THE BOARD
            double computerChoiceXd = Math.floor(Math.random() * 10); // using
                                                                        // Math.random
                                                                        // functions
                                                                        // for
                                                                        // computers
                                                                        // first
                                                                        // guess
                                                                        // to be
                                                                        // a
                                                                        // random
                                                                        // num
            double computerChoiceYd = Math.floor(Math.random() * 10);
            int computerChoiceX = (int) computerChoiceXd;
            int computerChoiceY = (int) computerChoiceYd;

            if (board[computerChoiceX][computerChoiceY] == 1) { // checking if
                                                                // math.random
                                                                // landed on a
                                                                // ship point
                System.out.println("Computer got a hit at " + computerChoiceX
                        + " " + computerChoiceY);
                board[computerChoiceX][computerChoiceY] = 2; // setting the
                                                                // point as 2 or
                                                                // 'hit'
                boardGraphical[computerChoiceX][computerChoiceY] = 'H';
                for (int row = 0; row < 10; row++) { // printing out graphical
                                                        // board using the same
                                                        // method as when
                                                        // intializing
                    for (int col = 0; col < 10; col++) {
                        System.out.print(boardGraphical[row][col]);
                    }
                    System.out.println(" "); // spacer for printing
                }

                Caculations test = new Caculations(computerChoiceX, // Creating
                                                                    // a new
                                                                    // object of
                                                                    // calculation
                        computerChoiceY, board);
                test.findShip();
                // break;

                if (board[3][3] == 2) { // checking to see if ship is sunk using
                                        // a triple if statement
                    if (board[3][4] == 2) {
                        if (board[3][5] == 2) {
                            System.out.println("Battleship sunk!");

                            continuePlay = false; // if so than it breaks out of
                                                    // loop to end the game
                            break;
                        }
                    }

                }
            } else if (board[computerChoiceX][computerChoiceY] == 0) { // otherwise
                                                                        // if
                                                                        // the
                                                                        // area
                                                                        // is a
                                                                        // 0 or
                                                                        // 'unmarked'
                System.out.println("Computer missed  at " + computerChoiceX
                        + " " + computerChoiceY);
                boardGraphical[computerChoiceX][computerChoiceY] = 'x'; // mark
                                                                        // area
                                                                        // as a
                                                                        // miss
                for (int row = 0; row < 10; row++) { // print out board
                    for (int col = 0; col < 10; col++) {
                        System.out.print(boardGraphical[row][col]);
                    }
                    System.out.println(" ");
                }

            }

        }

    }

}





public class Caculations {
    int xValue;
    int yValue;
    int[][] myArray;
    int[][] storage = new int[10][10];
    boolean xAxisChangeP;
    boolean yAxisChangeP;
    boolean xAxisChangeN;
    boolean yAxisChangeN;
    boolean notSunk;

    Caculations(int x, int y, int[][] myArray) {
        xValue = x;
        yValue = y;
        xAxisChangeP = true;
        yAxisChangeP = true;
        xAxisChangeN = true;
        yAxisChangeN = true;
        notSunk = true;

    }

    void findShip() {
        while (notSunk == true) {
            // 1
            while (xAxisChangeP == true) {
                if (myArray[xValue + 1][yValue] == 1) {
                    myArray[xValue + 1][yValue] = 2;
                    if (myArray[3][3] == 2) {
                        if (myArray[3][4] == 2) {
                            if (myArray[3][5] == 2) {
                                System.out.println("Battleship sunk!");
                                notSunk = false;

                            }
                        }
                    }
                    continue;
                }

                else {
                    xAxisChangeP = false;

                }

            }
            while (xAxisChangeN == true) {
                if (myArray[xValue - 1][yValue] == 1) {
                    myArray[xValue - 1][yValue] = 2;
                    if (myArray[3][3] == 2) {
                        if (myArray[3][4] == 2) {
                            if (myArray[3][5] == 2) {
                                System.out.println("Battleship sunk!");
                                notSunk = false;

                            }
                        }
                    }
                    continue;
                }

                else {
                    xAxisChangeN = false;
                }
            }

            // 1
            while (yAxisChangeP == true) {
                if (myArray[xValue][yValue + 1] == 1) {
                    myArray[xValue][yValue + 1] = 2;
                    if (myArray[3][3] == 2) {
                        if (myArray[3][4] == 2) {
                            if (myArray[3][5] == 2) {
                                System.out.println("Battleship sunk!");
                                notSunk = false;

                            }
                        }
                    }
                    continue;
                }

                else {
                    yAxisChangeP = false;

                }

            }
            while (yAxisChangeN == true) {
                if (myArray[xValue][yValue - 1] == 1) {
                    myArray[xValue][yValue - 1] = 2;
                    if (myArray[3][3] == 2) {
                        if (myArray[3][4] == 2) {
                            if (myArray[3][5] == 2) {
                                System.out.println("Battleship sunk!");
                                notSunk = false;

                            }
                        }
                    }
                    continue;
                }

                else {
                    yAxisChangeN = false;
                }
            }
        }
    }
}
Bob Mc Muffins.
  • 37
  • 2
  • 2
  • 11

3 Answers3

3

Have you initialized myarray? Best is debug your code to see, which statement throws the exception. In eclipse you can add NullPointerExeption as your breakpoint and debug.

maheeka
  • 1,983
  • 1
  • 17
  • 25
2

You use myArray, but you never initialize it.

public class Caculations {
   int xValue;
   int yValue;
   int[][] myArray;  // array declared but never initialized

   // ....

   void findShip() {
      while (notSunk == true) {
         // 1
         while (xAxisChangeP == true) {
            if (myArray[xValue + 1][yValue] == 1)  // then you use it here

Solution: initialize variables before using.

More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks for the help Hovercraft! I really apreciate it. Also, ill deffinetly read up more about that. I actually just started Java from a book and I was just doing this for fun so I probably wasnt ready to atempt a complicated program like this. – Bob Mc Muffins. Nov 26 '14 at 04:47
  • Ok sorry i have a new problem, when i run it now after intializing the array it just gets 1 hit than freezes and dosnet execute anything more. If you get a chance could you please look at my code and help find the problem? – Bob Mc Muffins. Nov 26 '14 at 04:51
0

In your constructor for Calculations, you never initialized myArray:

Caculations(int x, int y, int[][] myArray) {
    xValue = x;
    yValue = y;
    xAxisChangeP = true;
    yAxisChangeP = true;
    xAxisChangeN = true;
    yAxisChangeN = true;
    notSunk = true;
    this.myArray = myArray; //Add this line
}

This is a direct answer to your problem, but all in all, you should do some research regarding the meaning behind the exception that was thrown so you understand what it means.


Why this problem happened

In Java, all objects and primitives, if not initialized manually, are given a default value. For default values of primitives, check this: Primitive Data Types

In case of non-primitive types - such as Object, String, Thread, etc, as well as any user-defined class (i.e. Calculations) and also arrays (i.e. myArray) - the default value is null.

With that in mind, inside your constructor, as exemplified above, you have not initialized myArray, which means that when this variable was accessed for the first time, the value returned was null.


So, what's the problem with null?

Well, by itself, it does no harm. It's there. It doesn't bother you. Until you decide to use a variable that doesn't have an object assigned to it, but somehow you forget that and treat it as if it held something like a String or an array.

That's when Java will tell you: "Hey! There's no object here. I can't work like this. Let's throw an exception!".

victorantunes
  • 1,141
  • 9
  • 20
  • Wow! Thank you so much @victorantunes for such a thorough explanation. This really helps alot and it was nice of you to take the time and effort to read my code and give a great answer. I really appreciate your help! – Bob Mc Muffins. Nov 26 '14 at 06:01