3
I’ve been trying to compare a string (right answer) for an alternative question as an example in a project I’m developing, but I can’t succeed in all the different ways I try.
The goal is that every wrong answer given, the alternatives are shuffled and, as long as the person does not respond to the correct alternative, the loop is repeated.
The options - a, b, c, d, e - remains untouchable. Only the text of the alternatives are scrambled. The question is simple but is exemplified.
I’m using the .get()
by means of the for
which returns me from 0 to 4 for each element of ArrayList
. It is at that moment that the comparison by means of the switch
next to the variable boolean
appears not to be working, despite Collections.shuffle
function correctly with every wrong attempt. For example if I test outside the scope of (a,b,c,d and).
Just follow my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean acertou = false;
List<String> questao = new ArrayList<String>();
questao.add("Porta OR");
questao.add("Porta XOR");
questao.add("Porta AND");
questao.add("Porta NOR");
questao.add("Porta NOT");
String opcaoCorreta = "Porta NOT", opcaoString;
char opcao;
do {
for (int i = 0; i < 5; i++) {
questao.get(i);
}
System.out.println(
"(Conceitos de Computação) Que porta lógica utilizamos para inverter o sinal lógico recebido?\n");
System.out.println("a) " + questao.get(0));
System.out.println("b) " + questao.get(1));
System.out.println("c) " + questao.get(2));
System.out.println("d) " + questao.get(3));
System.out.println("e) " + questao.get(4));
System.out.println("\nResposta: ");
opcaoString = input.next();
opcao = opcaoString.charAt(0);
switch (opcao) {
case 'a':
if (opcaoCorreta.equals(questao.get(0))) {
acertou = true;
}
break;
case 'b':
if (opcaoCorreta.equals(questao.get(1))) {
acertou = true;
}
break;
case 'c':
if (opcaoCorreta.equals(questao.get(2))) {
acertou = true;
}
break;
case 'd':
if (opcaoCorreta.equals(questao.get(3))) {
acertou = true;
}
break;
case 'e':
if (opcaoCorreta.equals(questao.get(4))) {
acertou = true;
}
break;
if (acertou == true) {
System.out.println("Resposta correta");
} else {
System.out.println("Resposta incorreta");
Collections.shuffle(questao);
}
} while (!acertou);
input.close();
} }
EDIT: Use of break
within the if
in switch-case
consisted the big code problem, this now tidied up and running with the equals.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points, right after you give your acceptance).
– Maniero