简体   繁体   English

删除包含 next() 的 println 会导致无限循环?

[英]Removal of println containing next() causes an infinite loop?

I must be missing something obvious about how the various Scanner methods work but this really doesn't make any sense:关于各种 Scanner 方法的工作原理,我一定遗漏了一些明显的东西,但这真的没有任何意义:

this code causes an infinite loop:此代码导致无限循环:

Scanner valueScan = new Scanner(line);
valueScan.useDelimiter(",");
while(valueScan.hasNext())
{
count++;
}

while this code is valid:虽然此代码有效:

Scanner valueScan = new Scanner(line);
valueScan.useDelimiter(",");
while(valueScan.hasNext())
{
System.out.println("value token: " + valueScan.next());
cellCount++;
}

This is from Oracle's documentation I am not sure if it applies or what it means: "This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true. " (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#next%28%29)这是来自 Oracle 的文档我不确定它是否适用或它的含义:“此方法可能会在等待输入扫描时阻塞,即使先前调用 hasNext() 返回 true。”(http://docs.oracle .com/javase/1.5.0/docs/api/java/util/Scanner.html#next%28%29)

Because hasNext doesn't remove anything from the Scanner , so in your first case, you never change its state, hence the infinite loop.因为hasNext不会从Scanner中删除任何内容,所以在您的第一种情况下,您永远不会更改其 state,因此无限循环。 next extracts input, and hence changes the state of the Scanner . next提取输入,因此更改Scanner的 state。

The call to valueScan.next() in your second example is what makes the scanner move forward.在您的第二个示例中对valueScan.next()的调用是使扫描仪向前移动的原因。 hasNext() only checks that there is a next item in your scanner but doesn't do anything else, hence the infinte loop if there is at least one item. hasNext()只检查扫描仪中是否有下一个项目,但不做任何其他事情,因此如果至少有一个项目,则无限循环。

Without the next() the Scanner wont iterate.没有next() Scanner将不会迭代。

hasnext only tells you if next element is present and next goes to that element. hasnext仅告诉您下一个元素是否存在以及next是否转到该元素。

so in your first loop, it stays at the first element and keeps telling you that second element is present and does nothing more.所以在你的第一个循环中,它停留在第一个元素并不断告诉你第二个元素存在并且什么都不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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