Harry Potter
Harry Potter

Reputation: 11

How to read integers from a text file into a 2D Array?

I have integers in a text file, all separated by a space.

I know how to read in the file, but I don't know how to place the integers into the array. I know that I have to use parseInt somewhere.

The array is a 4x4. The integers are:

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

My code:

arr = new int [4][4];
IODialog input = new IODialog();
String location = input.readLine("Enter the full path of the configuration text file: ");
Scanner scn = null;
try {
  scn = new Scanner(new BufferedReader(new FileReader(location)));
  int i, j = 0;
  String line = scn.nextLine(); 
  String[] numbers = line.split(" "); 
} finally {
  if (scn != null) {
    scn.close();
   }
}

Upvotes: 0

Views: 11727

Answers (2)

Sanira
Sanira

Reputation: 334

This'll be helpful,

   int[][] a = new int[4][4];
   BufferedReader br = new BufferedReader(new FileReader("path/to/file"));

   for (int i = 0; i < 4; i++) {
        String[] st = br.readLine().trim().split(" ");
        for (int j = 0;j < 4; j++) {
            a[i][j] = Integer.parseInt(st[j]);
        }
   }

Upvotes: 3

frogbandit
frogbandit

Reputation: 571

You're on the right track.

Simply fill in your array right after you read in the next line from scanner.

 int[][] arr = new int[4][4];
 String location = input.readLine("Enter the full path of the configuration text file: ");
 scn = new Scanner(new BufferedReader(new FileReader(location)));

 String line = scn.nextLine(); 
 String[] numbers = line.split(" "); 

 for(int i = 0; i < 4; i++)
     for(int j = 0; j < 4; j++)
         arr[i][j] = Integer.parseInt(numbers[j]); 

This will read through your input line by line, and insert the integers in each line to complete your 4x4 array.

Upvotes: 1

Related Questions