簡體   English   中英

使用Scanner.nextInt()與Scanner.nextLine()進行異常處理

[英]Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()

這個問題僅出於教育目的。 我從Java教科書中獲取了以下代碼,並且很好奇為什么在catch塊中使用了input.nextLine()。

我試圖用input.nextInt()代替它來編寫程序。 該程序將不再正確捕獲異常。 當我傳遞非整數的值時,控制台顯示熟悉的“線程異常...”錯誤消息。

當我完全刪除該行代碼時,控制台將無休止地運行catch塊的System.out.println()表達式。

Scanner.nextLine()的用途是什么? 為什么每種情況的表現都不一樣?

import java.util.*;

public class InputMismatchExceptionDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean continueInput = true;

    do {
        try{
            System.out.print("Enter an integer: ");
            int number = input.nextInt();

            System.out.println(
                    "The number entered is " + number);

            continueInput = false;
        }
        catch (InputMismatchException ex) {
            System.out.println("Try again. (" +
                    "Incorrect input: an integer is required)");
            input.nextLine();
            }
        }
        while (continueInput);
    }   
}

感謝大家

當任何nextXxx(...)方法失敗時,掃描儀的輸入光標將重置為調用之前的位置。 因此,異常處理程序中nextLine()調用的目的是跳過“垃圾”數字……為下一次嘗試使用戶輸入數字做好准備。

並且當您刪除nextLine() ,代碼反復嘗試重新解析相同的“垃圾”編號。


還值得注意的是,如果nextInt()調用成功,則掃描器將立即定位在數字的最后一個字符之后。 假設您正在通過控制台輸入/輸出與用戶進行交互,則可能有必要或建議通過調用nextLine()使用其余的行(直到新行nextLine() 這取決於您的應用程序下一步要做什么。

暫無
暫無

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

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