I create a hangman game in java. I have no clue how to check and replace it. Everything works, the String word is correct and the gameboard is fine. So the game board give me the length of word as "_ _ _ _ _", for example.
Simply my Question is how I can I get the position of String word checked by the userinput and go to battleboard and change the "underline(_)" with the word wich find in the position.
public void gameStart(int topic) {
String[] wordList = this.wordList.chooseTopicArray(topic);
String word = this.wordList.pickRandom(wordList);
String gameboard = spielbrettvorbereiten(word);
Scanner userInput = new Scanner(System.in);
for (int i = 0; i <= 16;) {
System.out.println(gameboard);
System.out.print("Write a letter ");
String input = userInput.next();
int length = input.length();
boolean isTrue = letters.errateWortEingabe(length);
if (isTrue == true) {
if (word.contains(input)) {
}
} else {
i = i - 1;
}
i++;
}
I hope you guys can help me I am struggeling so hard.
Best Regards MichaelDev
There are several ways to implement hangman. I will show you an approach that is easy to understand, no focus on efficiency.
You need to know the final word and remember all characters that the user has guessed:
Now if a user guesses a character you should update the data-structures:
And last you need something that prints the word as
_ _ _ _
and so on. We do so by replacing all characters that are not contained incorrectChars
:The
replacePattern
may then look like(?i)[^aekqw]
. The(?i)
matches case insensitive, the[...]
is a group of symbols to match and the^
negates the group. So all characters that are not contained inside the[...]
get replaced.And a small check if the game has finished: