Examples of scanner errors in Java books?
I'm practicing HashSet from the Java books of cay S. Horstmann and Gary Cornell, and I think there's an error in the sample code on page 687 We have a word imported by scanner into HashSet, which looks like this (I deleted some unnecessary code to make a more obvious problem):
Set<String> words = new HashSet<String>(); Scanner in = new Scanner(system.in); while (in.hasNext()) { String word = in.next(); words.add(word); }
The problem is that there is no way to stop the cycle Or maybe something I'm missing?
To stop the loop, I added another static helper:
public static boolean isStop(Scanner in) { if (in.next().equals("stop")) { return true; } return false; }
Now the main code looks like this:
Set<String> words = new HashSet<String>(); Scanner in = new Scanner(system.in); while (!isStop(in)) { String word = in.next(); words.add(word); }
Is there any other way to stop the scanner from cycling? I can't believe the author of this book made a mistake?
Solution
Once this condition is false, the cycle stops:
in.hasNext()
That is, no more words
Inside the loop is a command to read the next word:
in.next()
Therefore, words will continue to be read until the scanner cannot read more words The loop will terminate at the end of anything the scanner is reading