gpt4 book ai didi

java - .hasNext() 无法正常工作

转载 作者:行者123 更新时间:2023-11-29 06:59:04 25 4
gpt4 key购买 nike

    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());

当我运行这段代码并输入:

Hi

在控制台打印这些:

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()); 什么也不打印,程序也没有结束。

如果您的 Scanner 从文件而不是标准输入读取数据,hasNext() 会在到达文件末尾时返回 false。

关于java - .hasNext() 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29227821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com