简体   繁体   中英

Reading 2D array from a text file

I want to read from a 2D array text file looking like this.This is the code that I wrote. I am creating a game board. The first line represents the dimensions of the board so the program must only read from the second line onwards.

I have attempted numerous ways of doing this such as using the scanner function etc. I was told by a friend of mine that my approach is wrong. How would I fix this code to do that particular function?

7 7
.......
.......
....x..
....x..
....x..
...xx..
...sx.t
public class hey {
    public static void main(String[]args) {

    }

    public static  String[][] read() throws IOException {
        BufferedReader bo = new BufferedReader(new("board_01.txt"));
        int column = Integer.parseInt(bo.readLine());
        int row = Integer.parseInt(bo.readLine());
        String[][] map = new String[row][column];
        for (int i = 0; i < row; i++) {
            String line = bo.readLine();
            for (int j = 0; j < column; j++) {
                map[i][j] = String.valueOf(line.charAt(j));
            }
        } 
        bo.close();
        return map;
    }
}

This is wrong:

int column = Integer.parseInt(bo.readLine());

int row = Integer.parseInt(bo.readLine());

This tries to read two ints on two separate lines, but that is not how your file is set up -- instead the 2 leading ints on one line, the first line

Instead you should have :

int column = bo.readInt();    
int row = bo.readInt();
bo.readLine();

You read the 2 ints in the first row, and the capture and swallow the end-of-line token so that the Scanner moves to the next line

Also, your main method cannot be empty, otherwise your program won't do anything at all.

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