当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Loop for many letter inputs

问题描述:

If the user accidentaly gives wrong input (letter), I want the program to loop again and again until the correct input is given, but with the below code I have some errors. Any ideas?

catch (InputMismatchException e) {

input.nextLine();

while (!input.hasNextInt()) {

System.out.print("Enter the number of people in the circle: ");

numberOfPeople = input.nextInt();

}

}

网友答案:

See the API:

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

This is caused because it's not reading the correct type.

I suggest you to use Scanner#hasNextInt() and to do something like this (Note that there is no usage of try-catch blocks):

if (input.hasNextInt()) {
    numberOfPeople = scanner.nextInt();
}
else {
    input.next();
    continue;
}

Why we use next()? Because of what the Java docs says about Scanner:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

网友答案:

Something like below can be done

for(int i=1;i<n;i++)
{
try
{
//code for taking the input from user
}
catch(InputMismatchException exception)
{
 //Equivalently keeping the same value of i 
--i;
}

}
分享给朋友:
您可能感兴趣的文章:
随机阅读: