Search code examples
javaswitch-statementdefault

How to make a user re-input data if input does not equal a case in the switch?


I recently learned Java and I have a switch statement that gets user input from another class and i was wondering how to make the default case for my switch statement make the user re-input data.

Currently I have the following basic code

static int getMonthInt(String monthName) 
{
    switch(monthName.trim()) 
    {
        case "January":
            return 1;
        case "Febuary":
            return 2;
        case "March":
            return 3;
        case "April":
            return 4;
        case "May":
            return 5;
        case "June":
            return 6;
        case "July":
            return 7;
        case "August":
            return 8;
        case "September":
            return 9;
        case "October":
            return 10;
        case "November":
            return 11;
        case "December":
            return 12;
        default:
            // what do i put here
    }
    
}

I get user input from an input class called from another class like so:

public static void main(String[] args) {

    String monthName;
    int dayNumber;
    int yearNumber;
    
    monthName = Input.getString("Please enter the current month name with a capital letter!");
    dayNumber = Input.getInt("Please enter the current day!");
    yearNumber = Input.getInt("Please enter the current year!"); }

This all works. My problem is however that if someone enters an invalid input such as 'ovtomber' I want the user to be re-prompted to enter data. Would I put this in the default case of the switch or in the main method (where I get user input) also how would i do this (I tried both ways and couldnt get the expected behavior & I could not find any topics on input validation)?


Solution

  • In your switch statement you have the default return an obviously invalid month (commonly -1):

    default:
        return -1;
    

    Then in your logic, you can request clarification if the result is -1, eg:

    int validatedMonth;
    do
    {
        monthName = Input.getString("Please enter the current month name with a capital letter!");
        validatedMonth = getMonthInt(monthName);
        if(validatedMonth == -1)
            System.out.println("Invalid month name, please try again");
    } while (validatedMonth == -1);
    

    (example code, I haven't checked it compiles)