escáner java única continuar si se detecta un número entero

PaPaB1nG0:

Estoy utilizando el escáner en Java y estoy tratando de conseguir el programa para continuar sólo si se detecta un número entero para la elección por parte del usuario, pero el código que he escrito no está dando esa funcionalidad. aquí está mi código:

import java.util.Scanner;

/**
 *
 * @author Ansel
 */
public class Test {

    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);

        AddressBook ad1 = new AddressBook();
        String firstName="";
        String lastName="";
        String key="";
        String street="";
        String city="";
        String county="";
        String postalCode="";
        String mNumber="";
        int choice=0;
      do{

        System.out.println("********************************************************************************");
        System.out.println("Welcome to the Address book. Please pick from the options below.\n");
        System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");

          System.out.print("Please enter a choice: ");
          int reloop = 0;
        do {
         try {
             scan.nextLine();
             choice = scan.nextInt();
              reloop ++; 
        } catch (Exception e) {
       System.out.println ("Please enter a number!");
  }} while(reloop == 0);

        if(choice==1){
            //Add user
            System.out.print("Please enter firstname: ");
            firstName=scan.next();
            System.out.print("Please enter lastname: ");
            lastName=scan.next();
            scan.nextLine();
            System.out.print("Please enter street:");
            street=scan.nextLine();
            System.out.print("Please enter city: ");
            city=scan.next();
            System.out.print("Please enter county: ");
            county=scan.next();
            System.out.print("Please enter postal code: ");
            postalCode=scan.next();
            System.out.print("Please enter Mobile number: ");
            mNumber=scan.next();
            Address address = new Address(street,city,county,postalCode,mNumber);
            key = lastName + " ".concat(firstName);
            Person person = new Person(firstName,lastName,address);
            ad1.addContact(key,person);
            System.out.println("key: " + key);
        }

        else if(choice==2){
            //Remove user

            System.out.print("Please enter name of user to remove: ");
            key=scan.nextLine();
            System.out.println("name:" + key);
            ad1.removeContact(key);  
        }

        else if(choice==3){
            //Edit user
        }

        else if(choice==4){
            //List contact
            System.out.println("Enter name of contact you wish to lookup: ");
            key=scan.nextLine();
            ad1.listContact(key);

        }

       else if(choice==5){
            //Sort contacts
        }
       else{
            System.out.println("Invalid choice entered, please try again");
       }

      }while(choice!=6);
    }
}

la principal pieza de código que no está funcionando correctamente es:

int reloop = 0;
        do {
         try {
             scan.nextLine();
             choice = scan.nextInt();
              reloop ++; 
        } catch (Exception e) {
       System.out.println ("Please enter a number!");
  }} while(reloop == 0);

este código cuando corrió pide que introduzca un número. si se introduce una letra, por ejemplo, se mostrará una línea en blanco hasta que se introduce otra carta y luego se dirá por favor, introduzca un número. No veo por qué no dice por favor, introduzca un número tan pronto como una carta u otra cosa que no sea un entero está presente

arcadeblast77:

Sólo tiene que utilizar Scanner.nextLiney Integer.parseInty ahorrarse la confusión.

Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.print("Please enter a choice: ");
int reloop = 0;
do {
  try {
    String input = scan.nextLine(); // Scan the next line from System.in
    choice = Integer.parseInt(input); // Try to parse it as an int
    reloop++;
  } catch (Exception e) {
    System.out.println("Please enter a number!");
  }
} while (reloop == 0);

También es posible usar nextLinedespués de cada nextIntde interrumpir la línea, pero prefiero analizar el intpor separado, como el anterior. Es más claro y detallado.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=336162&siteId=1
Recomendado
Clasificación