Zackary Zackary - 1 month ago 7
Java Question

How to read a file into an array

I am trying to read a file into an array using the code shown below. My issue is that I believe when referencing the elements in my array, I'm referencing empty elements so I'm unsure as to why my file is not being properly copied into the array. The file and code is all in the same file.

int column = 0;
int arraySize = 0;
String fileName = "SuperBowlWinners.txt";
File file = new File(fileName);
Scanner inputFile = new Scanner(file);

while (inputFile.hasNext()) {
inputFile.nextLine();
arraySize++;
}
String[][] superBowl = new String[arraySize][1];
while (inputFile.hasNext()) {
for (int index = 0; index < superBowl.length; index++) {
superBowl[index][0] = inputFiles.next();
superBowl[index][1] = inputFiles.nextLine();
}
}


The first while loop is used to determine the array size and I need to two columns, so that's why 1 is in the second []. Is the instance not being created between with the file? How do I allow the data to be read into the array from the file?

Answer
String[][] superBowl = new String[arraySize][1];
while (inputFile.hasNext()) {
    for (int index = 0; index < superBowl.length; index++) {
        superBowl[index][0] = inputFiles.next();
        superBowl[index][1] = inputFiles.nextLine();
    }
}

Well... the above code needs to be updated.

String[][] superBowl = new String[arraySize][2];
file = new File(fileName);
inputFile = new Scanner(file);
while (inputFile.hasNext()) {
    for (int index = 0; index < superBowl.length; index++) {
        superBowl[index][0] = inputFiles.next();
        superBowl[index][1] = inputFiles.nextLine();
    }
}

It's because:

  1. You want to have two columns,
  2. You read at the beginning till the end of the file, so you need to start reading from the beginning again.