如何持续捕获异常直到它正确 java

How to keep catching an exception until it's correct java

我正在编写一个使用扫描器 class 的程序,并希望使用 try-catch 块来捕获 InputMismatchExceptions。这是我写的:

public class StudentInfo{

 public static void main(String[] args){
    Scanner scnr = new Scanner(System.in);
    int creditHours = 0;
    try
     {
       System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)");
       creditHours = scnr.nextInt();
     }
    catch(InputMismatchException e){
       System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS");
       Scanner input = new Scanner(System.in);
       creditHours = input.nextInt();
    }
    String studentClass = checkStudent (creditHours);
    System.out.println("Official Student Classification: " + studentClass);
    }

try-catch 块工作一次,例如,如果我第一次输入 24.5,它会捕获异常并让用户重新输入他们拥有的学时数,但如果他们重新输入第二次为非整数,它无法再次捕获错误并发送适当的消息。所以基本上,我想知道是否有任何方法可以继续捕获异常并发送错误消息,无论他们尝试了多少次。我试过使用 do-while 循环或 while 语句,但它不起作用,是的。此外,我在 catch 块中创建了一个新的扫描器变量,因为如果没有,它不允许我在出于某种原因给出错误消息后输入新的整数。它确实会抛出我输入的错误,然后继续给我 Java 的 InputMismatchException 错误。

这是我尝试使用 while 循环的尝试:

int creditHours = 0;
    while(creditHours <= 0){
    try
     {
       System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)");
       creditHours = scnr.nextInt();
     }
    catch(InputMismatchException e){
       System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS");
       Scanner input = new Scanner(System.in);
       creditHours = input.nextInt();
    }
   }

    String studentClass = checkStudent (creditHours);
    System.out.println("Official Student Classification: " + studentClass);
  }

您需要 try-catch 处于循环中才能重新运行您的代码。

试试这个:

 public class StudentInfo{

 public static void main(String[] args){

    int creditHours = 0;
    boolean ok = false;
    System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)");

    while (!ok)
    {
        try
         {
           Scanner scnr = new Scanner(System.in);
           creditHours = scnr.nextInt();
           ok = true;
         }
        catch(InputMismatchException e){
           System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS");
        }
    }


    String studentClass = checkStudent (creditHours);
    System.out.println("Official Student Classification: " + studentClass);
    }