Estoy tratando de hacer que mi caja del interruptor vuelva a funcionar si obtienen el valor predeterminado

Aug 16 2020
    //Choice of choosing a dog or a cat

     String pet = input.next();

    switch (pet.charAt(0)) {
        case 'a' -> {
            System.out.println("What is your dog's name? ");
            String dogsName = input.next();
            System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
        }
        case 'b' -> {
            System.out.println("What is your cat's name? ");
            String catsName = input.next();
            System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
        }
        default -> System.out.println("That is not a valid option. Please choose again.");
    }

   input.close();

}

No puedo encontrar un bucle para usar que lo devuelva al caso ay repetidamente hasta que el usuario responda usando una de las opciones. ¡Cualquier ayuda sería increíble! Gracias

Respuestas

1 LoveshDongre Aug 17 2020 at 05:21

Usar do whilebucle es una forma sencilla de resolverlo.

Usé una variable repeatpara verificar, si necesito solicitar la entrada nuevamente o no

Además, tenga en cuenta que ahora, incluso si agrego otro caso (digamos case 'c'), no necesito modificar la condición de mi do whileciclo

boolean repeat;
do {
    String pet = input.next();
    repeat = false;
    switch (pet.charAt(0)) {
        case 'a' -> {
            System.out.println("What is your dog's name? ");
            String dogsName = input.next();
            System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
        }
        case 'b'-> {
            System.out.println("What is your cat's name? ");
            String catsName = input.next();
            System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
        }
        default: System.out.println("That is not a valid option. Please choose again.");
        repeat = true;
    }
} while(repeat);
input.close();
AnveshK Aug 17 2020 at 05:24

El bucle es una buena solución, pero también puede usar los métodos recesivos en java.

public static void main(String[] args) {
    
        Scanner input = new Scanner(System.in);
    
    
        System.out.println("    Welcome To The Choices Game...    ");
        System.out.println("Please enter your name: " );
    
        String playerName = input.nextLine();
    
        System.out.println("What is " + playerName + "'s" + " favorite pet?");
        System.out.println("a. Dog \nb. Cat");
    
        //Choice of choosing a dog or a cat
    
        method();
   
    
      input.close();
    
 }

public void method()
{

         String pet = input.next();
    
        switch (pet.charAt(0)) {
            case 'a' -> {
                System.out.println("What is your dog's name? ");
                String dogsName = input.next();
                System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
            }
            case 'b' -> {
                System.out.println("What is your cat's name? ");
                String catsName = input.next();
                System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
            }
            default -> System.out.println("That is not a valid option. Please choose again.");
            method();
        }
       
}
Srinjoy_Chatterjee37 Aug 17 2020 at 05:11

Para hacer un bucle en toda la sección de la caja del interruptor, puede intentar ponerlo en un bucle do-while. En cuanto a la condición para usar con el bloque do-while, puede probar: -do {...}while(pet.charAt(0)!='a' || pet.charAt(0)!='b');

Le proporciono una posible solución a continuación: -

   public static void main(String[] args) {

    Scanner input = new Scanner(System.in);


    System.out.println("    Welcome To The Choices Game...    ");
    System.out.println("Please enter your name: " );

    String playerName = input.nextLine();

    System.out.println("What is " + playerName + "'s" + " favorite pet?");
    System.out.println("a. Dog \nb. Cat");

    //Choice of choosing a dog or a cat

    do{
     String pet = input.next();

    switch (pet.charAt(0)) {
        case 'a' -> {
            System.out.println("What is your dog's name? ");
            String dogsName = input.next();
            System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
            break;}
        case 'b' -> {
            System.out.println("What is your cat's name? ");
            String catsName = input.next();
            System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
            break;}
        default -> System.out.println("That is not a valid option. Please choose again.");
    }
   
}while(pet.charAt(0)!='a' && pet.charAt(0)!='b');

  input.close();

}