J'ai besoin d'aide avec le code suivant:
int seatNum = 0;
Scanner seatNumber = new Scanner(System.in);
do
{
try
{
System.out.println("Please choose a seat number");
seatNum = seatNumber.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 7");
}
} while (seatNum <= 0 || seatNum >= 7);
4 Réponses :
int seatNum = 0;
Scanner seatNumber = new Scanner(System.in);
do {
try {
System.out.println("Please choose a seat number");
seatNum = seatNumber.nextInt();
}
catch(InputMismatchException e) {
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 7");
seatNumber.nextLine();
}
} while ( (seatNum <= 0 || seatNum >= 7) );
add seatNumber.nextLine(); in the catch block. This command advances the scanner to the next line (when reading from a file or string, this simply reads the next line), thus essentially flushing it, in this case. It clears the buffer and readies the scanner for a new input.
Idéalement, vous devez également ajouter une sorte de message de défaillance de validation dans le numéro de cas ne figure pas dans la plage.
Essayez ceci
String seatNum = null;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println(" Enter a number between 0 and 7");
seatNum = scanner.nextLine().toString();
if(seatNum.matches("[0-7]")) break; // makes sure user enter a number also between the range
else System.out.println("Enter between 0 and 7");
C'est encore mieux. Je devais juste le convertir en un entier après cela, car il passe par un tableau plus tard dans le programme. Merci
@Softy Oui, vous devez l'analyser à INT, je ne sais pas si vous avez compris les matchs ("[0-7") ou non, cela s'appelle une expression régulière, regex est plutôt pratique que vous devriez les avoir dans votre boîte à outils
@Softy je peux la rendre encore plus courte et meilleure
Vous pouvez le changer comme ceci:
int seatNum = 0;
Scanner seatNumber = new Scanner(System.in);
do
{
try
{
System.out.println("Please choose a seat number");
try{
seatNum = Integer.parseInt(seatNumber.next());
}catch (Exception ignored){}
}
catch(InputMismatchException e)
{
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 7");
}
} while (seatNum <= 0 || seatNum >= 7);
Soit vous pouvez utiliser BufferDreader ou utiliser un scanner avec un siège supplémentaire.Number () avec une explication ci-dessus donnée par @ Lazy.coder