Je souhaite que l'utilisateur entrave un numéro numérisé par le code suivant:
Scanner scanner = new Scanner(System.in); while(true) { try { System.out.println("Please enter a number: "); int input = scanner.nextInt(); System.out.println(input); //statements break; } catch(InputMismatchException | NumberFormatException ex ) { continue; } }
3 Réponses :
mettre scanner scanner = nouveau scanner (système.in); code> dans votre
pendant code> boucle.
Scanner scanner;
while(true) {
try {
System.out.println("Please enter a number: ");
scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("I said a number...");
}
}
Ce que vous avez dit fonctionne, mais j'ai défini l'objet du scanner sur la méthode elle-même. En d'autres termes, c'est une variable de classe. Existe-t-il un moyen de le faire sans créer l'objet dans la déclaration TRAIT-CATCH?
Bien sûr, il suffit de rétablir le même objet chaque boucle. Voir la modification.
Que diriez-vous de cela?
while(true) { try { System.out.println("Please enter a number: "); Scanner scanner = new Scanner(System.in); int input = scanner.nextInt(); System.out.println("\n\nEntered number is : " + input); break; } catch(InputMismatchException | NumberFormatException ex ) { System.out.println("\n\nInput was not a number. Please enter number again : "); } catch(Exception e ) { System.out.println("\n\nException caught :: " + e); } }
La réponse à mon problème est la suivante:
Scanner scanner = new Scanner(System.in); while(true) { try { System.out.println("Please enter a number: "); int input = scanner.nextInt(); System.out.println(input); //statements break; } catch(InputMismatchException | NumberFormatException ex ) { scanner.next();//new piece of code which parses the wrong input and clears the //scanner for new input continue; } }
Vous devrez peut-être réinitialiser le scanner
code> (je n'ai aucune expérience réelle avec la classe, mais je l'ai vu fait d'autre où), essayez
scanner.reset () code> avant le
continuer code>
Vous voudrez peut-être jeter un coup d'œil à << a href = "http://stackoverflow.com/questions/3059333/validating-input-utilisant-java-util-scanner" titre = "validation de la saisie à l'aide de Java Util Scanner"> Stackoverflow .com / questions / 3059333 / ... >