簡體   English   中英

在 While 循環中進行 Try-Catch

[英]Try-Catch inside While Loop

下面的代碼詢問用戶他/她想要多少賽車手。

while (true) { // loops forever until break
    try { // checks code for exceptions
        System.out.println("How many racers should" + " participate in the race?");
        amountRacers = in.nextInt();
        break; // if no exceptions breaks out of loop
    } 
    catch (InputMismatchException e) { // if an exception appears prints message below
        System.err.println("Please enter a number! " + e.getMessage());
        continue; // continues to loop if exception is found
    }
}

如果在amoutnRacers = in.nextInt(); 代碼跳出循環,程序的其余部分運行良好; 但是,當我輸入諸如“awredsf”之類的內容時,它應該捕獲該異常,它確實如此。 它沒有再次提示用戶,而是連續循環,這對我來說沒有意義。

程序在連續循環時打印如下:

應該有多少賽車手參加比賽? 應該有多少賽車手參加比賽? 應該有多少賽車手參加比賽? 應該有多少賽車手參加比賽? 應該有多少賽車手參加比賽? 應該有多少賽車手參加比賽? 應該有多少賽車手參加比賽?請輸入一個數字! null 請輸入一個數字! null 請輸入一個數字! null 請輸入一個數字! null 請輸入一個數字! null 請輸入一個數字! null 請輸入一個數字! 無效的 ...

我不明白發生了什么amountRacers = in.nextInt(); 那么為什么用戶不能輸入數字呢?

捕獲 InputMismatchException 后,只需添加input.next()

catch (InputMismatchException e) { //if an exception appears prints message below
    System.err.println("Please enter a number! " + e.getMessage());
    input.next(); // clear scanner wrong input
    continue; // continues to loop if exception is found
}

您需要清除錯誤的輸入,而掃描儀不會自動清除。

今天我解決了這個問題:-) 這是我的代碼。 我認為我有幫助

public int choice () throws Exception{
    Scanner read = new Scanner(System.in));
    System.out.println("Choose the option from the upper list");
    int auxiliaryChoiceMenu = 5;
    int auxiliaryVariable = -1;
    boolean auxiliaryBoolean = false;
    while (!auxiliaryBoolean) {
        try {
            auxiliaryVariable = read.nextInt();
            read.nextLine();
        } catch (Exception e) {
            System.out.println("incorrect data, try again"+e);
            read.nextLine();
            continue;
        }

        if (auxiliaryVariable<0 || auxiliaryVariable>auxiliaryChoiceMenu){
            System.out.println("incorrect data, try again");
        } else {
            auxiliaryBoolean = true;
        }
        choiceMenu = auxiliaryVariable;

    }
        return choiceMenu;
        //choicemenu is a external variable
}

您可能需要創建一個 Scanner 類來獲取從鍵盤流式傳輸的標准輸入。 您應該在代碼中的某處創建一個 Scanner 類的實例,例如: Scanner in = new Scanner(System.in); 所以你聲明中的“ in ”變量:amountRacers = in.nextInt(); 等待並掃描從鍵盤輸入的輸入並將其存儲。

為什么要使用帶有 try 和 catch 的循環?

我的建議是始終使用 try 和 catch 和while 或 do while loop ,這樣您就可以要求用戶重復他/她的輸入。 它還取決於您已經使用的循環和/或代碼的結構。

例如,如果您已經有一個 do while 循環,那么我建議您簡單地調整/修改您現有的循環。

我將發布一些示例,說明如何在用戶提供錯誤輸入后使用循環來重復輸入。

請參閱以下示例:

示例 1

Scanner input = new Scanner(System.in);
int exampleInput = 0;
do {
    try {
        System.out.print("\nEnter an integer from 1 to 25: ");
        exampleInput = input.nextInt();
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer from 1 to 25");
        input.next(); // Clear scanner buffer of wrong input
    }
} while (exampleInput < 1 || exampleInput > 25);
System.out.println("Print exampleInput: " + exampleInput);

示例 2

Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDone = false;
do {
    try {
        System.out.print("\nEnter an integer: ");
        exampleInput = input.nextInt();
        isDone = true;
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer");
        input.next(); // Clear scanner buffer of wrong input
    }
} while (!isDone);
System.out.println("Print exampleInput: " + exampleInput);

示例 3

Scanner input = new Scanner(System.in);
int exampleInput; // Here you don't need to initialize this variable because you don't need it as a condition for the loop.
boolean isDoneLoop2 = false;
while (!isDoneLoop2) {
    try {
        System.out.print("\nEnter an integer: ");
        exampleInput = input.nextInt();
        isDoneLoop2 = true;
    }
    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Wrong input! Enter an integer");
        input.next(); // Clear scanner buffer of wrong input
    }
}
System.out.println("Print exampleInput: " + exampleInput);

這對我有用。

while (true) {
        try {
            System.out.print("Ingrese la cantidad de puestos de atención: ");
            int puestos = Integer.parseInt(scn.nextLine());
            break;
        }
        catch (NumberFormatException e) {
            System.out.println("Ingrese un valor correcto");
            scn.reset();
            continue;
        }
    }

暫無
暫無

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

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