You are better off writing the code like this:
while(true){
try{
int level = scan.nextInt();
if(level==1){
System.out.println("You selected level 1!");
break;
}else if(level==2){
System.out.println("You selected level 2!");
break;
}else if(level==3){
System.out.println("You selected level 3!");
break;
}else{
System.out.println("That's not an option!");
continue;
}
}catch(InputMismatchException input){
System.out.println("That's not an option!");
continue;
}
}
continue
will immediately resume execution of the loop at the top, and break
will immediately jump too the closing brace }
of the while. This removes the use of the i
counter variable, which was entirely useless to the code. Also, this code will never run indefinitely, unless the user indefinitely enters improper values!
Hope this helped, good luck!