user1547386
user1547386

Reputation: 91

Reading File into 2 d array

my file called "s1" im trying to read into my program

0 0 5 1 0 0 2 0 8
0 0 0 0 7 0 0 4 9
7 8 0 0 2 0 6 0 5
0 9 0 7 6 2 0 0 0
0 4 7 0 0 0 8 9 0
0 0 0 9 8 4 0 2 0
9 0 8 0 3 0 0 5 1
5 7 0 0 1 0 0 0 0
6 0 3 0 0 9 7 0 0

i need to place those numbers into a 2d array but i keep getting a 9x9 of each line of code and i cant figure out why? my code:

public void Read(String s) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(s));
        String line = " ";
        String[] temp;

        while ((line = br.readLine()) != null) {
            temp = line.split(" "); //split spaces



            for(int i=0;i<board.length;i++){
                for(int j=0;j<board.length;j++){
                    board[i][j]=Integer.parseInt(temp[j]);

                }

        }

and my outputx 9 when i try to print it but replaced with every line:

603009700
603009700
603009700
603009700
603009700
603009700
603009700
603009700
603009700

what do i need to fix this problem ?

Upvotes: 0

Views: 35

Answers (1)

rgettman
rgettman

Reputation: 178333

You are looping over both dimensions of the array for each line, so the last line is the only one that populates the contents. What you are currently doing is, for each line, you copy the line's contents to every row.

You need to have only one j for loop for each line. The while loop can increment i once each loop instead of having an i for loop inside of it. That is, keep i constant in each while loop, incrementing it only at the end, to prepare for the next loop.

Upvotes: 2

Related Questions