繁体   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