king123456
king123456

Reputation: 1

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;
    }
}

Upvotes: 0

Views: 113

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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.

Upvotes: 1

Related Questions