Game of Old Doubt

Asked

Viewed 60 times

-1

I have the following method:

        void selecionarBloco() {
        
            while (blocoSelecionadoCorretamente == false) {
                   System.out.print("Qual casa você irá marcar (" + jogador +"):");
                   int blocoSelecionado = teclado.nextInt();
            
                   if (blocos[blocoSelecionado].equals("X") || blocos[blocoSelecionado].equals("O")) {
                        System.out.println("BLOCO JÁ SELECIONADO!");
                        blocoSelecionadoCorretamente = false;
                   } else {
                        blocoSelecionadoCorretamente = true;
                        blocos[blocoSelecionado] = jogador;             
                   }
              }
        }

When I put it to work the game of a very strange bug making 9 moves automatically and giving draw. I wonder what’s wrong.

Method: As long as the lockSelected is false, it will do the following commands, ask the user for a home, and place it inside lockSelected, after which it will test them to see if the selected house is already occupied, if yes it returns lockSelectionCorrectly = false, if not lockCorrectly = true, ending the method.

1 answer

1


In your question, you are omitted where you created the variable blocoSelecionadoCorretamente, I believe it’s out of function selecionarBloco()

If this is the case, since blocoSelecionadoCorretamente is true, every time next selecionarBloco() it is called it will pass directly from while, create it in the first line of your function can work

boolean blocoSelecionadoCorretamente = false;

However, I recommend trying differently:

When creating a Boolean type Variabel, you can use break to step out of a loop instantly, would look like this:

void selecionarBloco() {
    
        //Deixa o loop infinitamente até que break seja chamado
        while (true) {
               System.out.print("Qual casa você irá marcar (" + jogador +"):");
               int blocoSelecionado = teclado.nextInt();
        
               if (blocos[blocoSelecionado].equals("X") || blocos[blocoSelecionado].equals("O")) {
                    System.out.println("BLOCO JÁ SELECIONADO!");
               } else {
                    blocos[blocoSelecionado] = jogador;             
                    break;
               }
          }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.