How to compare these 2 arrays within this while?

1

I am developing a game similar to Forca, 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 that the user sees on the screen (which may not show all the letters), and the variable palavraSeparada is an array of characters that corresponds to the word that the user must guess

I'm doubtful about the while loop below. How do I check if the contents of the two arrays are the same?

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;
        }
    }
}
    
asked by anonymous 16.06.2015 / 22:45

1 answer

2

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

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

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 code, we still need to increment errou if if that is within for does not enter once. This I leave to you to solve, but it is easy. :)

    
16.06.2015 / 23:01