本文介绍了如何清除 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();

推荐答案

您无法明确清除扫描仪的缓冲区.在内部,它可能会在读取令牌后清除缓冲区,但这是 porgrammer 无法实现的实现细节.

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 中的扫描仪缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:51