1

I am attempting to run a Sudoku game code in java (Using NetBeans) and am currently writing the method that initializes the game and reads the file containing the starting game code. The text file reads as so:

0,0,2,9,8,0,5,0,0
4,0,0,0,7,0,0,1,3
0,3,9,6,0,4,0,7,0
2,0,0,0,5,6,4,0,0
8,4,0,3,0,0,2,0,1
9,0,7,0,0,1,0,8,6
6,0,0,7,0,5,1,3,0
0,9,1,4,0,0,0,0,5
0,2,0,0,3,0,6,0,8

My current code being run is:

        Scanner f = new Scanner(new FileReader("C:(MY FILE LOCATION)"));
        for (int i = 0; i < 9; i++) {
            line = f.next();
            readLine = line.split(",");
            for (int j = 0; j < 9; j++) {
                gameBoard[i][j] = readLine[j];
            }
        }

The NullPointerException comes from the line of code:

gameBoard[i][j] = readLine[j];

When I don't declare the numbers to the game board and just print them out instead it works just fine. I already having it throwing FileNotFoundException. Thanks for any help!

AJ Murgia
  • 15
  • 3
  • Please read: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Turing85 Feb 23 '20 at 21:24
  • @Turing85 I understand what it is and I understand what my code is producing, but I don't know what could possibly be triggering this exception. – AJ Murgia Feb 23 '20 at 21:27
  • 1
    Why don't you print the various variables right before your error – NomadMaker Feb 23 '20 at 21:37

1 Answers1

1

Here is the code I came up with to work:

String[][] gameBoard = new String[9][9];

Scanner f = new Scanner(new FileReader("C:\\Users\\milk\\Desktop\\twoD.txt"));

for(int i = 0; i < 9; i++)
{
    String line = f.next();
    String[] readLine = line.split(",");

    for(int j = 0; j < 9; j++)
    {
        gameBoard[i][j] = readLine[j];
    }
}

for(int i = 0; i < gameBoard.length; i++)
{
    for(int j = 0; j < gameBoard[i].length; j++)
    {
        System.out.print(gameBoard[i][j] + " ");
    }
    System.out.println();
}

Make sure that the gameBoard has 9 as the row and 9 as the column, and it is successfully entered into the array. Hope this helps :)

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52