Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

On Lab07, why am I getting this error: NoSuchElementException?

+4 votes
Here is the output that I got:

Enter text file name to read:
What would you like to do?
1 Find the sentence with the fewest words
2 Find the sentence with the most words
3 Create a new file with one sentence per line.
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at SentenceFinder.getNextSentence(SentenceFinder.java:42)
    at SentenceFinder.findShortestSentence(SentenceFinder.java:87)
    at SentenceFinder.startMenu(SentenceFinder.java:211)
    at SentenceFinder.main(SentenceFinder.java:19)
asked Feb 9, 2015 in (Winter 14) by Rose Peterson (100 points)

1 Answer

+2 votes

(Sorry this response is a bit late... evidently your classmates aren't checking the Q&A frequently enough!)

This happens when you try to read from a Scanner, but there is no input to get.  In particular, it happens when the scanner reaches the end of the file, and tries to consume more tokens after that.

To fix this, your getNextSentence(...) method needs to add a check for "&& input.hasNext()" to the while loop, to make sure that there is still more file to be read.

(For this particular sentence reading program, this is particularly a problem for files that don't end with punctuation...)

answered Feb 10, 2015 by Forrest Stonedahl (3,308 points)