1

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

我写了这个方法:

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()只有当输入中有下一个单词时才应该是真的,所以当没有其他单词时它应该停止。

4

2 回答 2

3

System.in是一个输入流。它永远不会关闭,因此对于 #hasNext() 将始终返回 true

于 2013-09-30T19:07:13.507 回答
0

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

于 2013-09-30T19:17:03.003 回答