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.