Search code examples
javaexceptiontry-catchinputmismatchexception

Java- handle an inputMisMatch exceptions


I am a new programmer and I am very inexperienced with exception handling as I am a student. I am writing a program that lets a users schedule appointments from the times of 1 - 6 o'clock. If the user enters a value anything other than an integer I want the program to tell the user that there was an error with his/her input and that it should be changed to an integer value, not double, String, char, etc. Here is my code below:

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;
    }
}

Also, by the way- I am not completely sure if it is actually an inputMisMatch exception or something else, but if it isn't please let me know, as I am a beginner. Thank you all!


Solution

  • so from your code snippet I am guessing you are using a scanner/BufferedReader setup of some sorts. A good way to check for integer input would be to use them "Integer.parseInt()" function (See: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)) and if this cannot parse the input into a valid integer it will throw a "NumberFormatException" which you can then catch and handle! Hope this helps!