How to compare these 2 arrays inside this while?

Asked

Viewed 70 times

1

I am developing a game similar to Hangman, where the user has to hit the word chosen by the computer in up to 8 attempts.

The variable mascara is an array of characters that corresponds to the word the user sees on the screen (which may not display all letters) and the variable palavraSeparada is a character array that matches the word the user should guess

I’m in doubt in the loop while below. How do I check if the content of the two arrays is equal?

while(acertou==false&&errou<8){

    for(int i=0;i<mascara.length;i++){
        System.out.print(mascara[i]);
    }

    System.out.println("");
    letraDigitada = input.nextLine().charAt(0);

    for (int i=0;i<palavraSeparada.length;i++){
        if (letraDigitada == palavraSeparada[i]){
            mascara[i]=letraDigitada;
        }
    }
}
  • This is to implement a game of Mastermind (AKA Password)? What is the content of palavraSeparada? What is the expected content of mascara?

  • @Lucasgoeten I have taken the liberty of adding an introductory text to give more context to those who are seeing this issue. If you disagree with something or want to add some more information, just click on the edit link.

1 answer

2

First, instead of acertou==false, use !acertou.

Second, use the method equals(char[], char[]) class java.util.Arrays.

Your code should look like this:

while (!acertou && errou < 8) {

    for (int i = 0; i < mascara.length; i++) {
        System.out.print(mascara[i]);
    }

    System.out.println("");
    letraDigitada = input.nextLine().charAt(0);

    for (int i = 0; i < palavraSeparada.length; i++) {
        if (letraDigitada == palavraSeparada[i]) {
            mascara[i] = letraDigitada;
        }
    }

    if (Arrays.equals(mascara, palavraSeparada)) acertou = true;
}

In the code, we still need to increase the errou in case the if that’s inside the for don’t enter once. I leave it to you to solve, but it’s easy. :)

Browser other questions tagged

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