Scanner scanner = new Scanner(System.in);
// check if the scanner has a token
System.out.println(scanner.hasNext());
// print the rest of the string
System.out.println(scanner.nextLine());
// check if the scanner has a token after printing the line
System.out.println(scanner.hasNext());
当我运行此代码并输入:
你好
在控制台中打印以下内容:
true
Hi
但从未程序结束或打印false
.怎么了?
/**
* 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()
hasNext()
块在等待输入时。这就是为什么第二次调用 System.out.println(scanner.hasNext());
什么都不打印并且程序不会结束的原因。
如果扫描程序从文件而不是标准输入读取数据,则hasNext()
到达文件末尾时将返回 false。
您正在从控制台读取数据,这就是为什么它不返回 false 值的原因。 而不是尝试从文件中读取数据,它肯定会起作用,因为当文件读取到达文件末尾时,它将返回 false,因为没有值。