Doubt with decision making

0

My dear ones, I have the following code:

  public static void questionTwo(){
    String back = "";
    Scanner scan = new Scanner(System.in);

    System.out.println("Questao 02: ");

    while(!back.equalsIgnoreCase("N") && !back.equalsIgnoreCase("NO")){
      System.out.println("TO DO");

      System.out.println("Deseja executar essa questao novamente? [Y/YES || N/NO]");
      back = scan.next();
    }
  }

So far, it works OK, assuming the user is not a retard. But let's suppose it is and type something other than Y / YES or N / NO

How do I return to System.out.println("Deseja executar essa questao novamente? [Y/YES || N/NO]"); if it types something other than what was proposed without repeating what is before it within while ?

    
asked by anonymous 30.09.2017 / 18:24

1 answer

2

Try this:

private static boolean estaDentro(String resposta, String... alternativas) {
    return Arrays.asList(alternativas).contains(resposta.toUpperCase(Locale.ROOT));
}

public static void questionTwo() {
    Scanner scan = new Scanner(System.in);

    repeteQuestao: while (true) {
        System.out.println("Questao 02: ");
        System.out.println("TO DO");

        while (true) {
            System.out.println("Deseja executar essa questao novamente? [Y/YES || N/NO]");
            String digitado = scan.nextLine();
            if (estaDentro(digitado, "N", "NO")) break repeteQuestao;
            if (estaDentro(digitado, "Y", "YES")) continue repeteQuestao;
            System.out.println("Não entendi o que você quis dizer, tente novamente.");
        }
    }
}

Also, put these two imports in the beginning:

import java.util.Arrays;
import java.util.Locale;

The estaDentro method checks whether the string of the first parameter ( resposta ) is one of the alternatives passed.

We have two while s. The only way out of while external (called repeteQuestao ) is by answering N or NO , which will cause a break in this loop to be executed. If the user answers Y or YES , the continue on the outer loop will be executed, which will cause the question to be repeated. Any other response will cause Deseja executar essa questao novamente? to be repeated as many times as necessary without the whole question being displayed until the user is no longer delayed (as defined).

The trick is that I'm naming the while outer loop so I can refer to it in break or continue later. This is a feature of the Java language that few people know about, but it is very useful in situations like this.

    
30.09.2017 / 19:28