简体   繁体   中英

Put text file to a 2D Array (Sudoku Grid)

I need to load a.txt file with int like 001 012 017 108 etc. -> 001 = means column 0, row 0, value 1. This is the code I have so far, the issue is finding a way to remove the space which are read as 0 and also print a new line for every rows. Thank you: Code so far: The output is. 12345678023456789034567891045678912056789123067891234078912345089123456091234567Exception in thread "main" java.lang:ArrayIndexOutOfBoundsException: -49

public static void main (String [] args) {
    int[][] sudokuGrid = new int [9][9];

    try {
        FileReader fichierALire = new FileReader("partie1.txt");
        int c = fichierALire.read();
        while (c != -1){
            int row = fichierALire.read();
            int value = fichierALire.read();
            fichierALire.read();
            sudokuGrid [c-48][row-48] = value-48;
            c = fichierALire.read();
            System.out.print(sudokuGrid[c-48][row-48]);
        }

    } catch (IOException exception) {
        System.out.println("Il y a une erreur lors de la lecture: " + exception.getMessage());
    }
}

}

Read the data line by line (instead of character by character).

the issue is finding a way to remove the space

Then as you read each line you can use the String.split(..) method.

It will then return you an Array of your values. Then you can iterate through each entry in the array and parse the value and populate your grid.

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