Try it like 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.");
}
}
}
Put also, these two Imports in the beginning:
import java.util.Arrays;
import java.util.Locale;
The method estaDentro
checks whether the string of the first parameter (resposta
) is one of the past alternatives.
We have two while
s. The only way out of the while
external (called the repeteQuestao
) is to answer N
or NO
, what will make a break
in this loop is executed. If the user responds Y
or YES
, the continue
in the external loop will be executed, which will cause the question to be repeated. Any other answer will make the Deseja executar essa questao novamente?
be repeated as many times as necessary without the entire question being displayed until the user is no longer delayed (according to its definition).
The trick is I’m naming the ribbon while
external to be able to refer to it in a break
or continue
later. This is a feature of the Java language that few people know, but which is very useful in situations like this.
Victor, and that’s right, but what I’m looking for would be more or less a filter. Imagine if the user type "exit" or "continue" for example? The idea was to return a message of the type; "Option invalid! nDigite Y para continuar e N para sair" ?
– Lucas
@Lucas edited the answer. I added a
System.out.println
at the end ofwhile
intern.– Victor Stafusa
I come from C#, many years on hold. But I don’t remember having the Break and Continue commands. I couldn’t fully understand the use of it, but I was amazed at what you did!
– Lucas