在 While 循环中尝试捕获 [英] Try-Catch inside While Loop

查看:25
本文介绍了在 While 循环中尝试捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码询问用户他/她想要多少赛车手.

The code below asks the user how many racers he/she would like.

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"之类的内容时,它应该捕获该异常,它确实做到了.它没有再次提示用户,而是不断循环,这对我来说没有意义.

If a number is entered at amoutnRacers = in.nextInt(); the code breaks out of the loop and the rest of the program runs fine; however, when I enter something such as "awredsf" it should catch that exception, which it does. Instead of prompting the user again it loops continuously, which to me does not make sense.

程序在连续循环时打印如下:

The program prints like this when looping continuously:

应该有多少车手参加比赛?应该有多少赛车手参加比赛?应该有多少赛车手参加比赛?应该有多少赛车手参加比赛?应该有多少赛车手参加比赛?应该有多少赛车手参加比赛?应有多少车手参加?请输入数字!空值请输入数字!空值请输入数字!空值请输入数字!空值请输入数字!空值请输入数字!空值请输入数字!空值...

How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race?Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null ...

我不明白发生了什么 amountRacers = in.nextInt(); 那么为什么用户无法输入数字?

I do not understand what is going on amountRacers = in.nextInt(); so why is the user not able to enter a number?

推荐答案

在捕获 InputMismatchException 后只需添加 input.next().

Just add input.next() once you catch InputMismatchException.

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
}

您需要清除错误的输入,扫描仪会自动不清除.

You need to clear the wrong input, which scanner automatically does not.

这篇关于在 While 循环中尝试捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆