Hi all,
I'm currently developing a hangman game for my assignment however one of my method does not give me the result i wanted.
Expected output with disguised word as HTML (case-insensitive)
The disguised word is **** Guess a character: h Incorrect. No. of guesses made is 1 with 1 wrong The disguised word is h*** Guess a character: m Incorrect. No. of guesses made is 2 with 2 wrong The disguised word is h*m* Guess a character: k Incorrect. No. of guesses made is 3 with 3 wrong The disguised word is h*m* Guess a character: t Correct. No. of guesses made is 4 with 4 wrong Good job, you found the secret word which is html
As seen in the output above input "h" & "m" should return Correct instead of incorrect.
Hangman.java
public class Hangman { private String secretWord; private String disguisedWord = ""; private String result; private int guesses = 0; private int wrongGuess = 0; public void setSecretWord(String word) { secretWord = word; } public void setDisguisedWord() { for (int i = 0; i < secretWord.length(); i++) { disguisedWord += "?"; } } public void guesses() { guesses++; } public boolean guessLetter(char c) { for (int i = 0; i < disguisedWord.length(); i++) { if (c == secretWord.charAt(i)) { disguisedWord = disguisedWord.substring(0, i) + c + disguisedWord.substring(i + 1); result = "Correct."; } else { result = "Incorrect."; } } wrongGuess++; if (secretWord.equals(disguisedWord)) { return true; } else { return false; } } public String getDisguisedWord() { return disguisedWord; } public String getResult() { return result; } public int getGuesses() { return guesses; } public int getWrongGuess() { return wrongGuess; } public String getSecretWord() { return secretWord; } }
Game.java
import java.util.Scanner; public class Game { public static void main(String[] args) { String word1 = "html"; String word2 = "css"; String word3 = "java"; Scanner kb = new Scanner(System.in); Hangman game = new Hangman(); game.setSecretWord(word1); game.setDisguisedWord(); System.out.println("Let's play a round of hangman."); System.out.println("We are playing hangman"); while (true) { System.out.println(""); System.out.println("The disguised word is " + game.getDisguisedWord()); System.out.println("Guess a letter:"); char guess = kb.next().charAt(0); game.guessCount(); boolean isFound = game.guessLetter(guess); if (isFound) { System.out.println(game.getResult() + " No. of guesses made is " + game.getGuesses() + " with " + game.getWrongGuess() + " wrong"); System.out.println("Good job, you found the secret word which is " + game.getSecretWord()); break; } else { System.out.println(game.getResult() + " No. of guesses made is " + game.getGuesses() + " with " + game.getWrongGuess() + " wrong"); } } } }