Scanner.hasNext()导致无限循环 [英] scanner.hasNext() results in an infinite loop

查看:110
本文介绍了Scanner.hasNext()导致无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,应该逐字读取输入的内容,并将该单词的长度递归地添加到ArrayList中(用于学校练习).

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).

我写了这个方法:

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();
    }
}

当我调用此方法时,它会不断询问新单词.它不会停止(递归)循环.为什么会这样呢? this.scanner.hasNext()仅在输入中有下一个单词时才为true,因此在没有其他单词时应停止.

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 是输入流.它永远不会关闭,因此对于#hasNext()

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

这篇关于Scanner.hasNext()导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆