Java Reference
In-Depth Information
Common Programming Error
Reading Beyond the End of a File
As you learn how to process input files, you are likely to write programs that
accidentally attempt to read data when there is no data left to read. For example,
the
CountWords
program we just saw uses a
while
loop to keep reading words
from the file as long as there are still words left to read. After the
while
loop,
you might include an extra statement to read a word:
while (input.hasNext()) {
String word = input.next();
count++;
}
String extra = input.next(); // illegal, no more input
This new line of code causes the computer to try to read a word when there is
no word to read. Java throws an exception when this occurs:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:817)
at java.util.Scanner.next(Scanner.java:1317)
at CountWords.main(CountWords.java:15)
As usual, the most important information appears at the end of this list of line
numbers. The exception indicates that the error occurred in line 15 of
CountWords
.
The other line numbers come from the
Scanner
class and aren't helpful.
If you find yourself getting a
NoSuchElementException
, it is probably because
you have somehow attempted to read beyond the end of the input. The
Scanner
is
saying, “You've asked me for some data, but I don't have any such value to give you.”
Common Programming Error
Forgetting
"new File"
Suppose that you intend to construct a
Scanner
the way we've learned:
Scanner input = new Scanner(new File("hamlet.txt"));
But you accidentally forget to include the
File
object and instead write this line
of code:
Scanner input = new Scanner("hamlet.txt"); // not right
Continued on next page
Search WWH ::
Custom Search