java扫描器。hasNext()导致无限循环
我有一段代码,它应该逐字读取输入,并将单词的长度递归地添加到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()
只应在输入中有下一个单词时为真,因此在没有其他单词时应停止
# 1 楼答案
System.in是一个输入流。它从不关闭,因此对于#hasNext()
# 2 楼答案
在Windows中使用
Ctrl+Z
(+Enter)或在Unix中使用Ctrl+D
发送EOF并终止输入流