在循环中尝试捕获

时间:2013-05-31 16:13:59

标签: java while-loop try-catch java.util.scanner

在下面的代码中,我要求用户给出一个整数输入,如果输入为0或负数,它会再次循环,直到给出正数。问题是,如果用户按下一个字母,我的代码会崩溃,尽管我在很多方面都使用了try-catch,但实际上没有任何效果。有任何想法吗? 我在循环中使用了try-catch,但它只适用于一个字母输入而且不正确。

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();

}

1 个答案:

答案 0 :(得分:4)

您当前代码中的问题是您总是尝试读取int,因此在接收非整数输入时,您无法以正确的方式处理错误。修改此项以始终阅读String并将其转换为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...
相关问题