-2

I'm working on programming my own tic tac toe game in javafx, but seem to have stumbled across some fundamental mechanic that I don't understand in dealing with classes. I tried to simplify my problem for this question. I just want to create a Game object containing a two dimensional string array and then print off the strings from that array through another class' method. I get a null pointer exception when I run this code. Any help would be greatly appreciated. Cheers.

package testing;

import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        Game g = new Game();
        g.addMove("X", 1, 0);
        g.addMove("O", 0, 1);
        GUI.printBoard(g);
    }

    public static void main(String[] args) {
        launch(args);
    }
}


package testing;

public class Game {
    private String[][] board;

    public Game() {
        this.board = new String[3][3];
    }

    public String[][] getBoard() {
        return this.board;
    }

    public void addMove(String s, int row, int col) {
        this.board[row][col] = s;
    }  
}


package testing;

public class GUI {

    public static void printBoard(Game g) {
        String[][] board = g.getBoard();

        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < 3; col++) {
                if (board[row][col].equals("X"))
                    System.out.println(board[row][col]);
                else
                    if (board[row][col].equals("O"))
                        System.out.println(board[row][col]);
            }
        }
    }
}
karma
  • 3
  • 1
  • Where's the nullpointerexception being thrown? Can you update it with a stack output so we can figure out the exact positions – ZeldaZach Jun 22 '17 at 15:59
  • You havent populated the whole 2d array, leaving slots where memory was never initialized, hence you are getting the null ptr exceptions in **printBoard(Game)** method where you try **board[row][col].equals("O")** or **board[row][col].equals("X")** , Cheers :) – ShayHaned Jun 22 '17 at 16:00
  • printBoard's function should be to print what's in the board and nothing else. you should really check for valid input in your addMove function – RAZ_Muh_Taz Jun 22 '17 at 16:04

1 Answers1

0

You have only assigned a value to the entries [1], [0] and [0], [1] of your array. Since your array is 3 by 3, the rest of the values will still be assigned null. When you are printing out the array's values, you are also iterating over the null values. Thus in the if you'll be trying to compare "X" to null which generates a NullPointerException.

Maarten Meeusen
  • 482
  • 1
  • 9
  • 23