J'ai le code suivant que j'utilise pour que l'utilisateur saisisse un entier, vérifiez que l'entrée est valide et, si ce n'est pas le cas, demandez une nouvelle saisie. Lorsque le code est exécuté, tout fonctionne correctement jusqu'à ce qu'une entrée non valide soit donnée, à quel point le code se bloque sans pause pour demander une nouvelle entrée jusqu'à ce qu'un débordement de pile se produise, et je ne sais pas pourquoi. Le code:Pourquoi cette méthode de saisie de l'utilisateur ne fonctionne-t-elle pas?
//Create the scanner object
private static Scanner in = new Scanner(System.in);
//Function to get input in integer form, complete with exception handling
//A value of -1 means the user is done inputing
public static int getInt()
{
int num;
//Begin try block
try
{
//Get the user to input an integer
num = in.nextInt();
//Make sure the integer is positive. Throw an exception otherwise
if (num < -1)
throw new InputMismatchException();
}
//If an exception occurred during the inputting process, recursively call this function
catch (InputMismatchException e)
{
System.out.println("Error: Input must be a positive integer, or -1.");
System.out.print("Enter a score: ");
num = getInt();
}
//Return the inputed number
return num;
}
+1 belle prise '' ' –
Cela le corrige. Merci beaucoup! – Lewis