在循环内尝试捕获 [英] Try-Catch inside a loop

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

问题描述

在下面的代码中,我要求用户提供一个整数输入,如果输入是0或负数,它将再次循环直到给出正数.问题是,如果用户按下字母,我的代码将崩溃,尽管我以许多方式使用了try-catch,但实际上没有任何作用.有任何想法吗? 我在循环中使用了try-catch,但是它只能用于一个字母的输入,而不能正常工作.

In the below code, I ask the user to give an integer input and if the input is 0 or a negative number, it loops again until the positive number is given. The thing is that if the users presses a letter, my code crashes and despite the fact that I used try-catch in a lot of ways nothing really worked. Any ideas? I used try-catch inside the loop, but it only worked for one letter input and not correctly.

System.out.print("Enter the number of people: ");

numberOfPeople = input.nextInt();

while (numberOfPeople <= 0) {

      System.out.print("Wrong input! Enter the number of people again: ");

      numberOfPeople = input.nextInt();

}

推荐答案

当前代码中的问题是,您始终试图读取int,因此在接收非整数输入时,您将无法处理错误的正确方式.修改它以始终读取String并将其转换为int:

The problem in your current code is that you're always trying to read an int so when receiving a non-integer input you can't handle the error in the right way. Modify this to always read a String and convert it into an int:

int numberOfPeople = 0;
while (numberOfPeople <= 0) {
    try {
        System.out.print("Enter the number of people: ");
        numberOfPeople = Integer.parseInt(input.nextLine());
    } catch (Exception e) {
        System.out.print("Wrong input!");
        numberOfPeople = 0;
    }
}
//continue with your life...

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

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