scanner.hasNext() results in an infinite loop

余生颓废 提交于 2019-12-11 12:29:15

问题


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.


回答1:


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




回答2:


Use Ctrl+Z(+Enter) in Windows or Ctrl+D in Unix to send EOF and terminate input stream



来源:https://stackoverflow.com/questions/19101776/scanner-hasnext-results-in-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!