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()方法會阻塞,不代表next()方法就不會阻塞。
/**
* 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
* <code>true</code>.
*
* @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();
}
}
第一個問題,兩段程式碼的差別在於阻塞的位置不同,加上一行輸出程式碼就可以很明顯地看到差異。
Test.java
另,hasNext()方法會阻塞,不代表next()方法就不會阻塞。
第二個問題,想要結束循環,在Windows環境下,需要輸入Ctrl+Z;而在Unix環境下,需要輸入Ctrl+D。請注意,這是輸入,而不是對控制台進行操作。這相當於向控制台輸入一個字符,這個字符代表EOF,此時hasNext()方法返回false,循環結束。
阻塞位置不一樣