Domanda

1) Il primo loop che devo usare è un do / while. In questo ciclo, l'utente viene richiesto di digitare una parola. Se l'utente digita la parola sbagliata ottengono un messaggio di errore:

non valido! Riprova! 2 tentativo (i) a sinistra!

non valido! Riprova! 1 tentativo (i) a sinistra!

Scusate! Non hai più tentativi lasciati!

Questa uscita funziona fino a quando la parola errata viene inserita ogni volta, ma se la parola corretta viene immessa dopo 1 tentativo fallito che applica ancora il messaggio di errore

2) All'interno del mio secondo loop (per ciclo) L'utente viene chiesto di inserire "3 * 8=" Questa parte del loop funziona bene se un numero errato viene inserito tutte le 3 volte o se 24 è inserito su qualsiasi tentativo.

Il problema è inserito nel ciclo dopo 24 anni. L'output è il seguente:

Grazie Blah Blah. Ti chiameremo a 55555555555 se sei un vincitore. 3 * 8= dove non deve essere visualizzato il 3 * 8. Mi rendo conto che potrei entrare in una pausa; Dopo questa affermazione, ma le istruzioni dicono specificamente che non posso usare il comando Break.

L'output corretto dovrebbe essere letto: Grazie Blah Blah. Ti chiameremo al 55555555555 se sei un vincitore.

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!" );
        }
    }
}
.

Spero di averlo reso abbastanza chiaro.

Per il riepilogo, ho bisogno di risolvere il problema con il mio do / pur non lasciarmi inserire la parola corretta dopo un tentativo fallito.

Inoltre, ho bisogno di sbarazzarmi del 3 * 8= mostrando dopo che gli utenti entrano nell'input corretto.

È stato utile?

Soluzione

Normalmente, si utilizza l'istruzione break, ma in quanto non è consentito l'impostazione dell'impostazione attempt = -1 avrà lo stesso effetto:

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

Modifica:

Sposta il do { } while(); in prima di if Check:

    // 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.
.

Altri suggerimenti

Penso che tu stia cercando di farlo.!

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);
    }
}
.

Prova a rompere il tutto in giù in funzioni molto piccole che fanno una cosa specifica ciascuno.Ad esempio, potresti avere una funzione che controlla solo se una parola è quella corretta, restituire 0 se lo è, o il numero di tentativi effettuati se non lo è.

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

È possibile effettuare una funzione che prende l'input dell'utente e chiama questa funzione per controllare detto input.Potrebbe quindi emettere un messaggio di errore dipendente dal codice di ritorno della funzione precedente.La funzione restituisce quindi un codice per dire la funzione sopra la situazione.

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;
    }
}
.

Infine, è possibile effettuare una funzione che contiene semplicemente il loop e tiene la logica per il mantenimento del ciclo:

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;
}
.

Poi in main, tutto ciò che devi fare è controllare se checkWord(String correctWord) restituito 0. Ripeti la stessa cosa per il tuo altro controllo (o potresti persino essere in grado di utilizzare alcune delle stesse funzioni), eseguendo un altro se all'interno del primo,ad esempio:

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

A meno che non mi manchi qualcosa, stai aspettando il primo input e se è sbagliato, stai andando in un ciclo di do-while e quindi non controllarti mai più se l'ingresso è corretto.

Devi spostare il se interno del ciclo 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);

}
.

Quando ottieni un risultato corretto, è necessario uscire dal loop.Questo viene fatto usando l'istruzione 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
}
.

Questo codice è incompleto, ma ha l'IDE che ti serviva,.provare,.

boolean strytry= true; boolean keeplooping= true;

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);
.

Faresti meglio all'utente una pausa per saltare fuori dal loop. Aothenwise the Loop continuerà, stampa "3 * 8=" e attendere il tuo ingresso. Se non vuoi usare una pausa, rendi anche il tentativo= -1 ha senso.

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);

         }
.

Bene, ovviamente devi rompere il ciclo esterno.

Quando hai una risposta corretta (cioè 'risposta== 24') nel blocco IF imposta una variabile booleana "haveanswer" a "true" (che viene inizializzata a "false" e controllare il loop esterno prima del sistema.Out.Print ("3 * 8="); 'per' 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);

}
}
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top