Pregunta

1) El primer bucle que necesito usar es hacer/mientras.En este bucle se le pide al usuario que escriba una palabra.Si el usuario escribe la palabra incorrecta, recibirá un mensaje de error:

¡Inválido!¡Intentar otra vez!¡Quedan 2 intentos!

¡Inválido!¡Intentar otra vez!¡Quedan 1 intento(s)!

¡Lo siento!¡No te quedan más intentos!

Esta salida funciona siempre que se ingrese la palabra incorrecta cada vez, pero si se ingresa la palabra correcta después de 1 intento fallido, aún se aplica el mensaje de error.

2) Dentro de mi segundo bucle (bucle for), se le pide al usuario que ingrese "3 * 8 = ". Esta parte del bucle funciona bien si se ingresa un número incorrecto las 3 veces o si se ingresa 24 en cualquier intento.

El problema radica en el bucle después de ingresar 24.El resultado es el siguiente:

Gracias bla, bla.Te llamaremos al 5555555555 si resultas ganador. 3 * 8 = Donde no debería mostrarse el 3 * 8.Me doy cuenta de que podría entrar en una pausa;después de esta declaración, pero las instrucciones dicen específicamente que no puedo usar el comando break.

La salida correcta debería ser: Gracias bla, bla.Te llamaremos al 5555555555 si resultas ganador.

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

    int attempt = 2;
    int answer = 24;
    long phoneNumber = 0;
    String firstName = "";
    String lastName = "";
    String wordOfTheDay = "";

    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();

    if(wordOfTheDay.equals("tired"))
    {
        for( attempt = 2; attempt >= 0; --attempt)
        {
            System.out.print(" 3 * 8 = ");
            answer = input.nextInt();
            input.nextLine();

            if( answer == 24)
            {
                System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

                firstName = input.next();
                lastName = input.next();
                phoneNumber = input.nextLong();

                System.out.printf(
                    "Thank you %s %s. We'll call you at %d if you're a winner.",
                    firstName,
                    lastName,
                    + phoneNumber);
            }

            else if( answer != 24)
            {
                if(attempt!=0)
                {
                    System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
                    continue;
                }
                else
                {
                    System.out.print( "Sorry!  You have no more attempts left!" );
                }
            }
        }
    }
    else
    {
        do
        {
            System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
            --attempt;
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();
        } while (attempt >= 1);

        if( attempt == 0)
        {
            System.out.print( "Sorry!  You have no more attempts left!" );
        }
    }
}

Espero haber dejado esto lo suficientemente claro.

En resumen, necesito solucionar el problema con mi do/mientras no me permite ingresar la palabra correcta después de un intento fallido.

Además, necesito deshacerme del 3 * 8 = que aparece después de que los usuarios ingresan la entrada correcta.

¿Fue útil?

Solución

Normalmente, usarías el break declaración, pero como no se le permite configurar attempt = -1 tendrá el mismo efecto:

if( answer == 24)
{
    ...
    attempt = -1; // An ugly 'break'
}

EDITAR:

Mueve el do { } while(); hasta antes if controlar:

    // These two lines of code are no longer required.
    //System.out.printf("Enter the word of the day:  ");
    //wordOfTheDay = input.nextLine();

    do
    {
        System.out.printf("Enter the word of the day:  ");
        wordOfTheDay = input.nextLine();

        if(!wordOfTheDay.equals("tired"))
        {
            System.out.printf(
                "Invalid! Try Again! %d attempt(s) left!\n ", --attempt);
        }
        else
        {
            attempt = 0; // Another ugly 'break'
        }
    } while (attempt >= 1);


    if(wordOfTheDay.equals("tired"))
    {
    }
    // Remove else branch as not required.

Otros consejos

creo que estás tratando de hacer esto.!

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int answer = 0;
        long phoneNumber = 0;
        String firstName = "";
        String lastName = "";
        String wordOfTheDay = "";

        int mainMenuAttempt = 3;
        do {
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();

            if (wordOfTheDay.equals("tired")) {

                int answerAttempt = 3;
                do {
                    System.out.print(" 3 * 8 = ");
                    answer = input.nextInt();
                    input.nextLine();
                    answerAttempt--;

                    if (answer != 24 && answerAttempt >0)
                        System.out.printf(
                                "Invalid! Try Again! %d attempt(s) left!\n ",
                                answerAttempt);

                } while (answerAttempt >0 && answerAttempt < 3 && answer != 24);

                if (answer == 24) {
                    System.out
                            .printf("Please enter your first name, last name, and phone number (no dashes or spaces)\n"
                                    + "in a drawing for an all-expenses-paid vacation in the Bahamas: ");

                    firstName = input.next();
                    lastName = input.next();
                    phoneNumber = input.nextLong();

                    System.out
                            .printf("Thank you %s %s. We'll call you at %d if you're a winner.",
                                    firstName, lastName, +phoneNumber);
                }

            }

            mainMenuAttempt--;

        } while (mainMenuAttempt >0 && mainMenuAttempt < 3 && !wordOfTheDay.equals("tired") && answer!=24);
        System.exit(0);
    }
}

Intente dividir todo en funciones muy pequeñas que hagan una cosa específica cada una.Por ejemplo, podría tener una función que simplemente verifique si una palabra es la correcta, devolviendo 0 si lo es, o el número de intentos realizados si no lo es.

private int checkWord(String correctWord, String wordToCheck, int attempts)
{
    if(wordToCheck.equals(correctWord))
    {
        return 0;
    }
    return attempts;
}

Luego, podría crear una función que tome la entrada del usuario y llame a esta función para verificar dicha entrada.Luego podría generar un mensaje de error dependiente del código de retorno de la función anterior.La función luego devolvería un código para informarle la situación a la función que se encuentra encima de ella.

public int checkWordVerbose(String question, String correctWord, int attempts)
{
    if(attempts <= 3)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print(question);
        String input = scan.nextLine();
        int failureCode = checkWord(correctWord, input, attempts);

        if(failureCode == 0)
        {
            return 0;
        } 
        else
        {
            System.out.println("Invalid! Attempts left: " + (3 - failureCode));
            return 1;
        }
    }
    else
    {
        System.out.println("Sorry! You have no more attempts left!\n");
        return 2;
    }
}

Por último, podría crear una función que simplemente contenga el bucle y contenga la lógica para mantener ese bucle:

public int checkWord(String correctWord)
{
    int failureCode = 1;
    int attempts = 1;
    do
    {
        failureCode = checkWordVerbose("Enter the word of the day: ", correctWord, attempts);
        attempts++;
    } while(failureCode == 1);
    return failureCode;
}

Luego, en principal, todo lo que necesitas hacer es verificar si checkWord(String correctWord) devolvió 0.Repita lo mismo para su otra verificación (o incluso podría usar algunas de las mismas funciones), realizando otra si está dentro de la primera, por ejemplo:

if(checkWord("tired") == 0)
{
    if(checkMath("24") == 0)
    {
        // Success!
    }
}

A menos que me esté perdiendo algo, está esperando la primera entrada y si está equivocado, va a ir en un bucle DO-WHILE y luego volver a verificar si la entrada es correcta.

Tienes que mover el IF dentro del bucle DO-WHILE:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int attempt = 2;
    int answer = 24;
    long phoneNumber = 0;
    String firstName = "";
    String lastName = "";
    String wordOfTheDay = "";

    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();
    do {
        if (wordOfTheDay.equals("tired")) {

            for (attempt = 2; attempt >= 0; --attempt) {
                System.out.print(" 3 * 8 = ");
                answer = input.nextInt();
                input.nextLine();

                if (answer == 24) {
                    System.out
                            .printf("Please enter your first name, last name, and phone number (no dashes or spaces)\n"
                                    + "in a drawing for an all-expenses-paid vacation in the Bahamas: ");

                    firstName = input.next();
                    lastName = input.next();
                    phoneNumber = input.nextLong();

                    System.out
                            .printf("Thank you %s %s. We'll call you at %d if you're a winner.",
                                    firstName, lastName, +phoneNumber);
                }

                else if (answer != 24) {

                    if (attempt != 0) {

                        System.out
                                .printf("Invalid! Try Again! %d attempt(s) left!\n ",
                                        attempt);
                        continue;
                    } else {

                        System.out
                                .print("Sorry!  You have no more attempts left!");
                    }
                }

            }

        } else {

            System.out.printf("Invalid! Try Again! %d attempt(s) left!\n ",
                    attempt);
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();
            if (!wordOfTheDay.equals("tired")) --attempt;

        }

    } while (attempt >= 1);

    if (attempt == 0) {

        System.out.print("Sorry!  You have no more attempts left!");
    }

    System.exit(0);

}

Cuando obtiene un resultado correcto, debe salir del bucle.Esto se hace utilizando la Declaración de break:

if( answer == 24)
{
    System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n" +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );
    firstName = input.next();
    lastName = input.next();
    phoneNumber = input.nextLong();
    System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);
    break;
    // that's the break statement
}

Este código está incompleto, pero tiene el IDE que necesita,.Tener un intento ,.

boolean firstry= verdadero; keeplooping booleano= verdadero;

do
    {
    if(!firstTry){
            System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
    }

        System.out.printf("Enter the word of the day:  ");
        wordOfTheDay = input.nextLine();
    if(wordOfTheDay.equals("hey!")){
        keepLooping = false;
    }
    --attempt;
    } while (attempt >= 1 && keepLooping);

Será mejor que un usuario es un descanso para saltar de la bucle. De lo contrario, el bucle continuará, imprima el "3 * 8=" y espere su entrada. Si no, no, no usas un descanso, haz que el attemp= -1 también tenga sentido.

if( answer == 24)
         {
            System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

        firstName = input.next();
        lastName = input.next();
        phoneNumber = input.nextLong();
        attempt = -1;
        System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);

         }

Bueno, obviamente tienes que romper el bucle externo.

Cuando tiene la respuesta correcta (es decir, 'Respuesta== 24') en el bloqueo de IF si se establece una variable booleana 'Haveanswer' a 'verdadero' (que se inicializa a 'Falso' y verifique el bucle externo antes del 'sistema.out.print ("3 * 8="); 'para' if (haveanswer) {break;} '

 enter code here`public static void main(String[] args)
 {

 Scanner input = new Scanner(System.in);

int attempt = 2;
int answer = 24;
long phoneNumber = 0;
String firstName = "";
String lastName = "";
String wordOfTheDay = "";


System.out.printf("Enter the word of the day:  ");
wordOfTheDay = input.nextLine();

if(wordOfTheDay.equals("tired"))
{
    boolean haveAnswer = false;
    for( attempt = 2; attempt >= 0; --attempt)
      {
        if (haveAnswer)
            break;
        System.out.print(" 3 * 8 = ");
        answer = input.nextInt();
        input.nextLine();

      if( answer == 24)
         {
            System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

        firstName = input.next();
        lastName = input.next();
        phoneNumber = input.nextLong();

        System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);

          haveAnswer = true;
          break;
         }

        else if( answer != 24)
        {

            if(attempt!=0)
            {

                System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
                    continue;
            }
            else
            {

                System.out.print( "Sorry!  You have no more attempts left!" );
            }
       }

     }

}
else
{
do
{

    System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
    --attempt;
    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();
} while (attempt >= 1);


  if( attempt == 0)
  {

     System.out.print( "Sorry!  You have no more attempts left!" );
  }
}

System.exit(0);

}
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top