簡體   English   中英

如何清除 Java 中的掃描儀緩沖區?

[英]How can I clear the Scanner buffer in 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.");

如何清除緩沖區?

編輯:我嘗試了以下操作,但由於某種原因它不起作用:

while(in.hasNext())
    in.next();

試試這個:

in.nextLine();

這使掃描儀前進到下一行。

您不能明確清除掃描儀的緩沖區。 在內部,它可能會在讀取令牌后清除緩沖區,但這是 porgrammers 無法觸及的實現細節。

使用以下命令:

in.nextLine();

緊接着

System.out.println("Invalid input. Please Try Again.");
System.out.println();

或在以下大括號之后(您對此有何評論)。

這個命令將掃描器推進到下一行(從文件或字符串讀取時,這只是讀取下一行),從而在這種情況下基本上刷新它。 它清除緩沖區並為新的輸入准備掃描儀。 當用戶輸入無效輸入(例如要求輸入數字時的字母)時,它可以優選地用於清除當前緩沖區。

該方法的文檔可以在這里找到: http : //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

希望這可以幫助!

這應該解決它...

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.");
            in.next(); // -->important
            System.out.println();
        }
        // Clear buffer
    }
    System.out.print(rounds+" rounds.");

其他人建議使用in.nextLine()清除緩沖區,這適用於單行輸入。 然而,正如評論指出的那樣,有時 System.in 輸入可以是多行的。

如果您使用的是 System.in 而不是其他一些 InputStream,您可以創建一個新的 Scanner 對象,在其中清除緩沖區。

in = new Scanner(System.in);

如果你這樣做,不要先調用in.close() 這樣做將關閉 System.in,因此您將在后續調用in.nextInt();獲得 NoSuchElementExceptions in.nextInt(); System.in 可能不應該在您的程序中關閉。

(上述方法特定於 System.in。它可能不適用於其他輸入流。)

如果您確實需要在創建新對象之前關閉 Scanner 對象,則此 StackOverflow 答案建議為 System.in 創建一個 InputStream 包裝器,該包裝器具有自己的 close() 方法,該方法不會關閉包裝的 System.in 流。 不過,這對於簡單的程序來說太過分了。

scan.nextLine();

在讀取字符串輸入之前放置上面的行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM