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;
}
}
This is because a letter will cause your
while(loop && kb.hasNextInt())
to befalse
. I suggest put anif
statement with thehasNextInt()
within thewhile
loop.Example (using a
while
loop instead ofif
statement to really try getting the number):