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());
Run Code Online (Sandbox Code Playgroud)
当我运行此代码并输入:
你好
在控制台中打印这些:
true
Hi
Run Code Online (Sandbox Code Playgroud)
但从来没有程序结束或打印.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()
Run Code Online (Sandbox Code Playgroud)
hasNext()等待输入时阻塞.这就是为什么第二次System.out.println(scanner.hasNext());打印没有打印,程序也没有结束.
如果您的扫描程序正在从文件而不是标准输入中读取数据,hasNext()则在到达文件末尾时将返回false.
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           642 次  |  
        
|   最近记录:  |