-4

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?

xenteros
  • 15,586
  • 12
  • 56
  • 91
Zackary
  • 3
  • 1

2 Answers2

1
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.
xenteros
  • 15,586
  • 12
  • 56
  • 91
1

If you are using java 8 you can use streams:

Files.lines(Paths.get(fileName)).toArray(String[]::new);
staszek
  • 251
  • 2
  • 9