【问题标题】:Try-Catch inside a loop循环内的 Try-Catch
【发布时间】:2013-05-27 12:45:36
【问题描述】:

在下面的代码中,我要求用户输入一个整数,如果输入是 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();

}

【问题讨论】:

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


    【解决方案1】:

    您当前代码中的问题是您总是试图读取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...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多