javaintswitch-statementvalidating

.hasNextInt() in switch statement


I'm basically trying to validate so that you can only enter an Integer. This is what I have at the moment, but if I type letters it goes through the switch and just leaves the result as blank.

I want it so that if anything other than an integer is entered it will go to default in the switch.

Any help would be great. Thanks!

while(loop && kb.hasNextInt())
{   

    choice = kb.nextInt();
    switch(choice)
    {
    case 1 :
            language = "FRENCH";
            loop = false;
            break;
    case 2 : 
            language = "GERMAN";
            loop = false;
            break;
    case 3 :
            language = "SPANISH";
            loop = false;
            break;
    default :
            System.out.println("That is not a correct choice. Please try again!");
            break;

    }
}   

Solution

  • This is because a letter will cause your while(loop && kb.hasNextInt()) to be false. I suggest put an if statement with the hasNextInt() within the while loop.


    Example (using a while loop instead of if statement to really try getting the number):

    while(loop)
    {
        // validate int using while loop
        while(!kb.hasNextInt())                             
        {
            System.out.println("you must enter a number! ");
            kb.next();
        }
    
        choice = kb.nextInt();
    
        switch(choice)
        {
        case 1 :
                language = "FRENCH";
                loop = false;
                break;
        case 2 : 
                language = "GERMAN";
                loop = false;
                break;
        case 3 :
                language = "SPANISH";
                loop = false;
                break;
        }
    }   
    
    System.out.println("Thank You " + studentID + " you have been registered for " + language);