簡體   English   中英

Scanner.reset()不起作用

[英]Scanner.reset() doesn't work

這段代碼應該從用戶獲得一個整數,然后完成程序。 如果用戶輸入的號碼無效,則會再次詢問用戶。

捕獲異常后,它使用Scanner.reset()重置掃描程序,但它不起作用。 並重新拋出先前的異常。

Scanner in = new Scanner(System.in);
while (true) {
    try {
        System.out.print("Enter an integer number: ");
        long i = in.nextLong();
        System.out.print("Thanks, you entered: ");
        System.out.println(i);
        break;
    } catch (InputMismatchException ex) {
        System.out.println("Error in your input");
        in.reset(); // <----------------------------- [The reset is here]
    }
}

我以為Scanner.reset()會重置所有內容並忘記異常。 我在詢問用戶輸入新內容之前先說了一下。

如果我說錯了,那么正確的方法是什么?

您誤解了reset方法的目的:它可以重置與掃描程序關聯的“元數據” - 它的空格,分隔符等。 它不會改變其輸入的狀態,因此無法實現您的目標。

你需要的是next()的調用,它從Scanner讀取並丟棄任何String

try {
    System.out.print("Enter an integer number: ");
    long i = in.nextLong();
    System.out.print("Thanks, you entered: ");
    System.out.println(i);
    break;
} catch (InputMismatchException ex) {
    System.out.println("Error in your input");
    in.next(); // Read and discard whatever string the user has entered
}

依靠異常來捕獲異常情況是可以的,但是在調用next...方法之前使用has...方法更好的方法是使用has... next...方法,如下所示:

System.out.print("Enter an integer number: ");
if (!in.hasNextLong()) {
    in.next();
    continue;
}
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;

Per Scanner.reset()javadoc ,該方法僅“重置”區域設置,基數和分隔符設置。 它對已讀取的數據沒有任何作用。

暫無
暫無

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

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