I wrote a function that scans a tab delimited file of baseball stats.
public static ArrayList dataRead() throws FileNotFoundException {
//ArrayList array = new ArrayList<ArrayList>();
Scanner s = new Scanner(new File("c:\\stats.txt")).useDelimiter("\r");
ArrayList<String> array = new ArrayList<String>();
int i = 0;
while(s.next() != null) {
String currentLine = s.next();
Scanner split = new Scanner(currentLine).useDelimiter("\t");
for(int j = 0; j < 16; j++) {
System.out.print(split.next() + " ");
j++;
}
System.out.println("\r");
}
s.close();
return array;
}
This function works until the end of the file. To my knowledge the while loop should close at the end of the file because it returns null, but I keep getting a noSuchElement error instead. If I could guarantee the file size, I would just use a for loop with the size, but I can’t because team size could technically vary. How would I properly end the file scanner while loop so I can close the scanner?
From: Javadocs for Scanner.next()
When there are no more lines left in the file, calling
s.next()throws aNoSuchElementExceptionexception. You’re also callings.next()twice, once in the while() and once inside the loop. You should really be calledwhile(s.hasNext())instead.