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

查看:145
本文介绍了在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天全站免登陆