java中hasnext的作用_java中Scanner的hasNext()的疑问
第一個(gè)問(wèn)題,兩段代碼的區(qū)別在于阻塞的位置不同,加上一行輸出代碼就可以很明顯地看到差別。
Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNext())
{
System.out.print("You inputted: ");
System.out.println(s.next());
}
}
}
另,hasNext()方法會(huì)阻塞,不代表next()方法就不會(huì)阻塞。
/**
* Returns true if this scanner has another token in its input.
* This method may block while waiting for input to scan.
* The scanner does not advance past any input.
*
* @return true if and only if this scanner has another token
* @throws IllegalStateException if this scanner is closed
* @see java.util.Iterator
*/
public boolean hasNext() {
ensureOpen();
saveState();
while (!sourceClosed) {
if (hasTokenInBuffer())
return revertState(true);
readInput();
}
boolean result = hasTokenInBuffer();
return revertState(result);
}
/**
* Finds and returns the next complete token from this scanner.
* A complete token is preceded and followed by input that matches
* the delimiter pattern. This method may block while waiting for input
* to scan, even if a previous invocation of {@link #hasNext} returned
* true.
*
* @return the next token
* @throws NoSuchElementException if no more tokens are available
* @throws IllegalStateException if this scanner is closed
* @see java.util.Iterator
*/
public String next() {
ensureOpen();
clearCache
while (true) {
String token = getCompleteTokenInBuffer(null);
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
if (needInput)
readInput();
else
throwFor();
}
}
第二個(gè)問(wèn)題,想要結(jié)束循環(huán),在Windows環(huán)境下,需要輸入Ctrl+Z;而在Unix環(huán)境下,需要輸入Ctrl+D。注意,這是輸入,而不是對(duì)控制臺(tái)進(jìn)行操作。這相當(dāng)于向控制臺(tái)輸入一個(gè)字符,這個(gè)字符代表EOF,此時(shí)hasNext()方法返回false,循環(huán)結(jié)束。
總結(jié)
以上是生活随笔為你收集整理的java中hasnext的作用_java中Scanner的hasNext()的疑问的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java3n 1_1005 继续(3n+
- 下一篇: spark java 计数_spark程