Java- 处理一个 inputMisMatch 异常

Java- handle an inputMisMatch exceptions

我是一名新程序员,作为一名学生,我对异常处理非常缺乏经验。我正在编写一个程序,让用户从 1 点到 6 点的时间安排约会。如果用户输入的值不是整数,我希望程序告诉用户 his/her 输入有错误,应该将其更改为整数值,而不是双精度、字符串、字符等. 下面是我的代码:

boolean created = false;
while (!created) {
    // Asks when you want your appointment
    System.out.println("When would you like your appointment?");
    int userTime = input.nextInt();

    try {
        /**
        * I really do not know what to put in here. If the user inputs things like
        * letters and symbols and doubles or floats, etc. I want the program to send a
        * message to the user saying that an integer value must enter an integer.
        */
        userTime = input.nextInt();
    } catch (InputMismatchException ime) {
        System.out.println("Error! Please enter an integer from 1 to 6. Letters and symbols are not allowed");
    }   

    /*
    * Checks if the time value is either not in range and not taken- than lets you
    * pass on to create the appointment and add it into the array
    */

    if (userTime < 1 || userTime > 6) {
        System.out.println("Time value not in range");
    } else if (appointments[userTime] != null) {
        System.out.println("Time already taken");
    } else {
        // Adds username into array of Appointments
        created = true;
        apTotal++;
        appointments[userTime] = name;
    }
}

此外,顺便说一下 - 我不完全确定它是否真的是 inputMisMatch 异常或其他原因,但如果不是,请告诉我,因为我是初学者。 谢谢大家!

所以根据您的代码片段,我猜您正在使用某种 scanner/BufferedReader 设置。检查整数输入的一个好方法是使用它们 "Integer.parseInt()" 函数(参见:https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)),如果它无法将输入解析为有效整数,它将抛出一个 "NumberFormatException",然后您可以捕获并处理它!希望这对您有所帮助!