20
I was doing an exercise for the university using the class Scanner
and something unusual happened, watch the code.
for(int i = 0; i < 11; i ++){
//problema(esta pulando a escolha de um dos jogadores, precisamente o jogador 1)
System.out.println(P[i]);
System.out.println("Jogador 1, faça a sua aposta:");
aposta1 = leitor.nextInt();
System.out.println("Jogador 2, faça a sua aposta:");
aposta2 = leitor.nextInt();
System.out.println("Jogador 1, insira a sua resposta:");
resposta1 = leitor.nextLine();
System.out.println("Jogador 2, insira a sua resposta:");
resposta2 = leitor.nextLine();
This code should accept the answers of both players, but see the output of the program:
Quanto é 2 + 2?
A- 1
B- 2
C- 3
D- 4
Jogador 1, faça a sua aposta:
10
Jogador 2, faça a sua aposta:
10
Jogador 1, insira a sua resposta:
Jogador 2, insira a sua resposta:
D
O jogador 1 errou
O Jogador 2 acertou
As you can see, the program skips the reader’s resposta1
not allowing me to put a reply, returning as empty. This kind of problem only happened after I entered the readers of the aposta1
and aposta2
, when they are removed the readers of the resposta1
and resposta2
are read normally.
As a solution I created another class Scanner
to the resposta1
and resposta2
separating readers, which in the end worked. However I was curious as to why the reader of the error while being used multiple times
From the method’s use description, it seemed to me that it advances a line of code and stops at the next use of the Scanner. That would be my explanation, I don’t know if you’re right.Try to use it.
leitor.next();
, at least it worked for me.– Gustavo Cinque