本文介绍了如何清除Java中的扫描程序缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的事情:
Scanner in=new Scanner(System.in);
int rounds = 0;
while (rounds < 1 || rounds > 3) {
System.out.print("How many rounds? ");
if (in.hasNextInt()) {
rounds = in.nextInt();
} else {
System.out.println("Invalid input. Please try again.");
System.out.println();
}
// Clear buffer
}
System.out.print(rounds+" rounds.");
如何清除缓冲区?
编辑:我尝试了以下内容,但由于某些原因它无效:
I tried the following, but it does not work for some reason:
while(in.hasNext())
in.next();
推荐答案
您无法明确清除扫描仪的缓冲区。在内部,它可能会在读取令牌后清除缓冲区,但这是在porgrammers的范围之外的实现细节。
You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.
这篇关于如何清除Java中的扫描程序缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!