samedi 31 octobre 2015

Scan in 2D array txt file in Java

When I scan in my 2d array text file, I get an exception error if I don't have a number in the first line. My text file is as follows:

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

The zero at the top, should not be there. However, I have found that if I take it out, my code doesn't work. The number doesn't have to be a zero, it works with any number as long as there is something there. Here is my code:

public static void main(String[] args) throws FileNotFoundException {
    String fileName = "Sudoku2d.txt";
    Scanner inputStream = null;
    System.out.println("The file " + fileName + "\ncontains the following lines:\n");
    inputStream = new Scanner(new File("C:\\Users\\ZachsLaptop\\Documents\\NetBeansProjects\\Sudoku\\Sudoku2d.txt"));
    String line = inputStream.nextLine();
    int[][] puzzel = new int[9][9];
    for (int row = 0; row < 9; row++) {
        for (int column = 0; column < 9; column++) {
            puzzel[row][column] = Integer.parseInt(line);
        }
    }

    while (inputStream.hasNextLine()) {
        line = inputStream.nextLine();
        System.out.println(line);
    }
    inputStream.close();

}

Here is my output with the zero at the top of the text file:

The file Sudoku2d.txt contains the following lines: (in a 9x9 matrix with commas separating numbers)

8, 3, 5, 4, 1, 6, 9, 2, 7
2, 9, 6, 8, 5, 7, 4, 3, 1
4, 1, 7, 2, 9, 3, 6, 5, 8
5, 6, 9, 1, 3, 4, 7, 8, 2
1, 2, 3, 6, 7, 8, 5, 4, 9
7, 4, 8, 5, 2, 9, 1, 6, 3
6, 5, 2, 7, 8, 1, 3, 9, 4
9, 8, 1, 3, 4, 5, 2, 7, 6
3, 7, 4, 9, 6, 2, 8, 1, 5
BUILD SUCCESSFUL (total time: 0 seconds)

Here is my code if I remove the zero:

The file Sudoku2d.txt contains the following lines:

I do not want to have to put a random number at the top of my text files for them to run. Can anyone please tell me why this is happening?

Aucun commentaire:

Enregistrer un commentaire