I have a piece of code which should read input word by word and add the length of the word to an ArrayList recursively (for a school exercise).
I wrote this method:
ArrayList<Integer> wordLengths = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
// ...
private void readWords() {
// read a word, if there are more words, read the next word
this.wordLengths.add(this.scanner.next().length());
if (this.scanner.hasNext()) {
readWords();
}
}
When I call this method, it keeps asking for new words. It won't stop the (recursive) loop. Why is this happening? this.scanner.hasNext()
should only be true when there's a next word in the input so it should stop when there is no other word.