This is an implementation of the Hangman game. Once the user has uncovered the word, the program should exit, but it continues to prompt the user for input although all letters of the word have been correctly guessed.
How can I make the program exit properly once the word has been guessed?
The word to seach is for example no
: Here is an illustration:
Enter your lettre:
n
The letter is OK !
n_
Enter your lettre:
o
The letter is OK !
no
Enter your lettre:
I don't understand why the loop continues ? Because I found the word...
Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Random r = new Random();
String[] arr = {"one", "no"};
String word = arr[r.nextInt(arr.length)];
char[] dash = word.toCharArray();
char[] charArr = word.toCharArray();
for(int i=0;i<dash.length;i++){
dash[i] = '-';
System.out.print(dash[i] + " ");
}
System.out.println("");
for(int i=0;i<3;i++){
System.out.print("Enter your letter : ");
char letter = input.next().charAt(0);
for(int j=0;j<charArr.length;j++){
if(letter == charArr[j]){
dash[j] = letter;
System.out.println("Ok ! ");
System.out.println(dash);
i--;
}
}
}
}
}
I share you the code here => https://repl.it/repls/BonyRevolvingOs
Thank you for your help.