Hi.. :?:

I have written a program that reads a file and loads it into the 2D matrix but the problem is that it only loads the first line into 2D Matrix and duplicates the same. Can somebody point out the mistake.

Here is my input file

14	12	5	4	6
10	9	4	3	10
9	5	2	13	2
14	14	10	12	2
9	1	3	12	2

Here is my faulty output:-

mazeLine = [[14, 12, 5, 4, 6], [14, 12, 5, 4, 6], [14, 12, 5, 4, 6], [14, 12, 5, 4, 6], [0, 0, 0, 0, 0]]

Below is my code:-

public class Reader {
    
    public Reader(){
    }

    public static void main(String args[]) throws FileNotFoundException, IOException{
        BufferedReader br = new BufferedReader(new FileReader("test.txt"));
        int[][] mazeLine = new int[0][];
        String line = br.readLine();
        String[] tokens = line.split("\t");
        //int width  = Integer.parseInt(tokens[0]);
        //int height = Integer.parseInt(tokens[1]);
        int width = 5;
        int height = 5;
        //line = br.readLine();
        //line = br.readLine();
        // use mazeLine to read in the grid data from the file
        mazeLine = new int[height][width];
        int row = 0;
        while((line = br.readLine()) != null) {
            //tokens = line.split("\t");
        // for(int row =0; row < tokens.length; row++)  {
            for(int j = 0; j < tokens.length; j++) {
                mazeLine[row][j] = Integer.parseInt(tokens[j]);
            }
         //}
            row++;
        }
        br.close();
        System.out.printf("mazeLine = %s%n", Arrays.deepToString(mazeLine));
        //Add first line into array
//        int firstLine = mazeLine.length;

    }
}

Thanks ;)

This article has been dead for over six months. Start a new discussion instead.