It's the scanner variable. You create it like this:
By default, a Scanner will split the input into tokens that are delimited by whitespace, no matter whether the whitespace is a space or a new line. This will cause scanner.nextInt() to return the next token as an int, no matter how your file is formatted, as long as each individual token is a valid integer and they are separated by whitespace and nothing else.
Be sure to declare the scanner and the reader inside the parentheses of the try-statement. It will ensure that the file is closed after you're done reading it.
Nice bit of code, but I think I would change this:-toIf you get any situation where you don't have a next int, that means the file has a line with 5 or 7 numbers in, or a non‑number, so the file is corrupt and you should stop reading. Should I throw a different sort of exception?
Campbell Ritchie wrote:If you get any situation where you don't have a next int, that means the file has a line with 5 or 7 numbers in, or a non‑number, so the file is corrupt and you should stop reading.
I don't agree. The formatting of the file itself is inconsequential. It's just a bunch of integers that get distributed over different lists.
If you want to deduce the number of columns from the formatting, you should probably perform some special processing on the first line first.
If you don't care that the number of integers is a multiple of the number of columns, but you still want to check that the input doesn't contain invalid tokens, you should probably do it like this:
Should I throw a different sort of exception?
InputMismatchException or an appropriate custom exception.