Basically, it’s for a hangman game and I initialize a guessed character char array of the same length of the word that’s to be guessed, but without putting anything in the array. After each guess, I want to add the guessed character to the array, and it will check whether or not the character has been guessed, but I’m having difficulty implementing this.
What I’ve tried is having this helper method in my Hangman class:
private boolean checkIfGuessed(char c) {
boolean guessed = false;
for (int i = 0; i < guessedChars.length; i++) {
if (guessedChars[i] == c) {
guessed = true;
break;
}
else if (guessedChars[i] != c && guessedChars[i] == 0) {
guessedChars[i] = c;
}
}
for (int i = 0; i < guessedChars.length; i++) {
System.out.print(guessedChars[i] + " ");
}
return guessed;
}
But it’s not doing what I’d like, it simply fills the array with whatever letter is first guessed. (e.g. no matter where the game is, if the player guessed a first, and the array was of length 6, it would be aaaaaa)
I’m trying to do this by having a variable to flag if it’s been guessed (and returning that to another method) and it’s set to guessed if it loops through the array and finds the same character at some index that was initially guessed and will break out. Otherwise, if a certain index isn’t equal to the character guessed, and it’s equal to 0 (I know in numerical arrays, this signifies empty, not sure if in char arrays), meaning empty, it will write the guessed letter to the index the loop is at.
Problem being obviously it loops through and seems to label all the indices in the array to the first character guessed.
Is there a better way to do this/what am I doing wrong?
You add the character in a loop and don’t exit the loop after you add it. As it stands now, you’d need to scan the entire array (since it’s unsorted), indicate if it was in the array by setting a flag or storing an index if found, and add it to the array if it wasn’t found.
Personally, I’d keep the guessed characters in a set.