Home > OS >  Filling an Array with a File
Filling an Array with a File

Time:10-01

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.

CodePudding user response:

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

}

CodePudding user response:

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.

  • Related