如果输入的是字符串而不是整数,则尝试使用 try/catch 返回无效语句

问题描述 投票:0回答:1

我想在此方法中使用 try/catch(整个类太长,所以我无法将其粘贴到此处)以在输入字符串而不是整数时捕获异常,因为它应该是。 我确实尝试实现它,但只是遇到 StackOverflowError 或 InputMismatchError。

谁能帮我解决一下?

代码如下:

private void manage() throws ParseException {
        System.out.println("Please select an operation");
        System.out.println("1. View Reservation Information");
        System.out.println("2. Manage Reservations");
        System.out.println("3. Manage Extra Services");

        int temp = scan.nextInt();
        
        if (temp==1) {
            viewRes();
        } else if (temp==2) {
            manageRes();
        } else if (temp==3) {
            manageExtra();
        } else {
            System.out.println("Invalid entry. Please enter 1, 2, or 3.");
            manage();
        }
        
        System.out.println("Continue?");
        System.out.println("1. Yes");
        System.out.println("2. No");

        temp = scan.nextInt();

        if (temp==1) {
            manage();
        } else if (temp==2) {
            System.out.println("Exiting application. Please wait a moment....");
        }
    }
java try-catch
1个回答
0
投票

如你所愿。

private void manage() throws ParseException {
    System.out.println("Please select an operation");
    System.out.println("1. View Reservation Information");
    System.out.println("2. Manage Reservations");
    System.out.println("3. Manage Extra Services");

    int temp = 0;
    
    try{
       temp = scan.nextInt();
    }
    catch(Exception e){
        temp = -1;
    }
    
    if (temp==1) {
        viewRes();
    } else if (temp==2) {
        manageRes();
    } else if (temp==3) {
        manageExtra();
    } else {
        System.out.println("Invalid entry. Please enter 1, 2, or 3.");
        manage();
    }
    
    System.out.println("Continue?");
    System.out.println("1. Yes");
    System.out.println("2. No");

    temp = scan.nextInt();

    if (temp==1) {
        manage();
    } else if (temp==2) {
        System.out.println("Exiting application. Please wait a moment....");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.