简体   繁体   中英

Reading a 2d array from a file in java

I have a text file that is 32x32 in size. For example first two lines:

11111111111111111111111111111111
11111111111111111111111111111000
...

I want to read and store this file in a 2D array. I have the following java code, but can't exactly figure out how to read the file data. I guess I would need two nested for loops?

public static int[][] readFile(){
BufferedReader br = null;
int[][] matrix = new int[32][32];
try {

    String thisLine;
    int count = 0;


    br = new BufferedReader(new FileReader("C:\\input.txt"));

    while ((thisLine = br.readLine()) != null) {

    //two nested for loops here? not sure how to actually read the data

    count++;
    }
    return matrix;                      


} 
catch (IOException e) {
    e.printStackTrace();
} 
finally {
    try {
        if (br != null)br.close();
        } 
    catch (IOException ex) 
        {
        ex.printStackTrace();
        }
}
return matrix;
}

Assuming that each line in your file is a row, and, for each row, a character is an entry:

// ...
int i,j;
i = 0;
while((thisLine = br.readLine()) != null) {
    for(j = 0; j < thisLine.lenght(); j++) {
        matrix[i][j] = Character.getNumericValue(thisLine.charAt(j));
    }
    i++;
}
// ...

This is just a starting point... there may be many more efficient and clean ways to do this, but now you have the idea.

You only need one more loop, since the while loop you already have is functioning as the outer loop.

while ((thisLine = br.readLine()) != null) {
    for(int i = 0; i < thisLine.length(); i++){
        matrix[count][i] = Character.getNumericValue(thisLine.charAt(i));;
    }

count++;
}

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