简体   繁体   中英

scanner.hasNext() results in an infinite loop

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.

System.in is an input stream. It is never closed, so it will always return true for #hasNext()

在Windows中使用Ctrl+Z (+ Enter)或在Unix中使用Ctrl+D发送EOF并终止输入流

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM