user3413170
user3413170

Reputation: 261

Java file to 2D array

I'm trying to create a 2D array from a .txt file, where the .txt file looks something like this:

xxxx            
xxxx                 
xxxx                 
xxxx                

or something like this:

xxx
xxx
xxx

So I need to handle multiple sizes of a 2D array (Note: Each 2D array will not always be equal x and y dimensions). Is there anyway to initialize the array, or get the number of characters/letters/numbers per line and number of columns? I do not want to use a general statement, something like:

String[][] myArray = new Array[100][100];

And then would filling the array using filewriter and scanner classes look like this?

File f = new File(filename);
Scanner input = new Scanner(f);
for(int i = 0; i < myArray[0][].length; i++){
  for(int j = 0; j < myArray[][0].length, j++){
    myArray[i][j] = input.nextLine();
  }
}

Upvotes: 1

Views: 118

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

You have several choices as I see it:

  1. Iterate through the file twice, the first time getting the array parameters, or
  2. Iterate through it once, but fill up a List<List<SomeType>> possibly instantiating your Lists as ArrayLists. The latter will give you much greater flexibility in the short and long run.
  3. (per MadProgrammer) The third option is to re-structure the file to provide the meta data required to make decisions about the size of the array.

For example, using your code,

  File f = new File(filename);
  Scanner input = new Scanner(f);
  List<List<String>> nestedLists = new ArrayList<>();
  while (input.hasNextLine()) {
     String line = input.nextLine();
     List<String> innerList = new ArrayList<>();
     Scanner innerScanner = new Scanner(line);
     while (innerScanner.hasNext()) {
        innerList.add(innerScanner.next());
     }
     nestedLists.add(innerList);
     innerScanner.close();
  }
  input.close();

Upvotes: 2

roeygol
roeygol

Reputation: 5028

Java Matrix can have each line (which is an array) by your size desicion.

You can use: ArrayUtils.add(char[] array, char element) //static method But before that, you need to check what it the file lines length

Either this, you can also use ArrayList> as a collection which is holding your data

Upvotes: 0

Related Questions