Java scanner.hasNext()的使用
我已经尝试了很多网站,但没有一个网站能让我正确使用JAVA中的hasNext()函数。我知道它会一直扫描到没有更多的输入?不再输入意味着什么?用户将已经知道它将提供多少输入。该功能何时停止?请帮助我理解这个函数。谢谢。如果您看到Scanner.class中的以下代码,您将知道您的答案Java scanner.hasNext()的使用,java,function,loops,Java,Function,Loops,我已经尝试了很多网站,但没有一个网站能让我正确使用JAVA中的hasNext()函数。我知道它会一直扫描到没有更多的输入?不再输入意味着什么?用户将已经知道它将提供多少输入。该功能何时停止?请帮助我理解这个函数。谢谢。如果您看到Scanner.class中的以下代码,您将知道您的答案 /** * Returns true if this scanner has another token in its input. * This method may block while waiting
/**
* 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);
}
如果您看到上面的代码ensureOpen()方法,请确保扫描仪处于打开或关闭状态,post状态已验证,这意味着在光标接收输入之前,它将使用参数验证info form Scanner构造函数
在这里,当您定义以下代码时
Scanner out = new Scanner(System.in);
在这里,创建新的扫描仪资源将系统输入作为一个流。下面的构造函数使用参数执行任务
/**
* Constructs a new <code>Scanner</code> that produces values scanned
* from the specified input stream. Bytes from the stream are converted
* into characters using the underlying platform's
* {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
*
* @param source An input stream to be scanned
*/
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN); // Below is the description
}
在上面注释标记的代码中,调用转到java.io.InputStream类,该类确保在用户提供输入之前从控制台读取数据
希望这对您有所帮助。以下是独家新闻:hasNext()会一直扫描,直到没有更多用户输入。这仅仅意味着,如果仍有剩余的输入需要扫描,程序将继续运行。扫描完所有用户输入后,它停止扫描。当输入块为空时,该功能停止。例如,假设您输入了5个输入。系统会一直运行,直到扫描完所有5个输入。它会告诉您输入是否包含其他令牌。若并没有,你们就到了河的尽头用户已经知道它将提供多少输入“在一般情况下是错误的。
Scanner
不仅仅用于需要用户输入的情况。您可以使用System.in
扫描用户输入控制台的数据,也可以使用FileInputStream
扫描文件内容。还有其他用途,比如扫描字符串。注意不要“尝试很多网站”。其中99%是垃圾。使用官方文档和教程。