I have to create a hangman game. I am stuck in the last step. In fact, when the user finds the word my input asks yet a letter.
Here an example: (the word to find is "non")
Enter your letter please : n
n _ n
Enter your letter please : o
n o n
Enter your letter please :
n o n
My problem is probably my wordFind
, I don't understand how to manipulate this ?
String[] words = {"yess", "non"};
String wordRandom = words[(int) (Math.random() * words.length)];
boolean[] letterGuess = new boolean [wordRandom.length()];
boolean wordFind = false;
int numberAttempt = 5;
while(numberAttempt > 0 && !wordFind){
System.out.println("Number of attempt(s) " + numberAttempt);
for(int i=0; i < wordRandom.length(); i++){
if(letterGuess[i]){
System.out.print(wordRandom.charAt(i));
}
else{
System.out.print("- ");
}
}
System.out.println(" ");
System.out.print("Enter your letter please : ");
char letter = input.next().charAt(0);
int letterFound = 0;
boolean alreadyFound = false;
for(int i=0; i < wordRandom.length(); i++){
if(wordRandom.charAt(i) == letter){
if(letterGuess[i]){
alreadyFound = true;
}
letterGuess[i] = true;
letterFound++;
}
}
if(alreadyFound){
System.out.println("Letter already proposed and it has been found ! ");
} else{
if(letterFound == 1){
System.out.println("The letter is correct ! ");
}
else if(letterFound > 0){
System.out.println("The letter is " + letterFound + " times in the word ! ");
}
else{
numberAttempt--;
System.out.println("The letter is not in the word ! ");
}
}
}
Please login or Register to submit your answer