0

So the program is supposed to read the file. The first two lines are the numbers that are to be used for setting up the rows and columns, while the rest are going to be stored inside the array.

4
5
1
3
5
7
12
34
56
78
21
44
36
77
29
87
48
77
25
65
77
2

I have used BufferReader to read information out of the file then compare them to other information coming in to the program, but this in particular is a little bit confusing.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
OEThe11
  • 341
  • 2
  • 11

2 Answers2

1

What I have understood from your question is that you want to create a 2 dimensional array using file. Where first and second line is row and column and remaining are the array values. I have written one program please check if it suits your requirement or not.

public class FileBufferedReader {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferReader = new BufferedReader(new FileReader("Your File Path"));
        int row = Integer.parseInt(bufferReader.readLine());
        int column = Integer.parseInt(bufferReader.readLine());
        int [][] arr = new int [row][column];

        for(int i=0;i<row;i++) {
            for (int j = 0; j < column; j++) {
                int x = Integer.parseInt(bufferReader.readLine());
                arr[i][j] = x;
            }
        }
        for(int [] a : arr){
            System.out.println(Arrays.toString(a));
        }
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
KapilGahlot
  • 166
  • 3
  • Don't just answer with code. Explain in detail what you're doing so the OP can learn from your answer. – Gilbert Le Blanc Sep 30 '21 at 18:14
  • I think I got it. Using readLine to read the first two lines and having the variables that it was stored in, assigned as the parameters to structure the 2D array. Then using the for loop to read the rest of the list and placing them in the 2D array. the last for loop is used to separate the inner array to the next line once the row is filled up. – OEThe11 Sep 30 '21 at 18:38
0

If you need to read the first two lines, you should only use the readline() method twice before the while, since the other data must be inserted into an array.

bad_coder
  • 11,289
  • 20
  • 44
  • 72