I am trying to make a Hangman game in Java, I use 3 Strings to process the game. randWord is the word randomly selected word from a designated word list array (WORD_LIST), randWordExt is the randWord in extended format (e.g. penguin -> p e n g u i n), and guessWord is the String that gets updated while the player guesses.
static String[] WORD_LIST =
{
//list of words implemented here
};
static String randWord;
static String randWordExt = "";
static String guessWord = "";
static int LIVES = 10;
This is my main method where the problem is, the while loops is not exiting when the word is completely solved. Hence the final message is never displayed. It loops through perfectly, guessing works, but when the word is solved it doesn't exit the loop or display the final message.
public static void main(String[] args) {
boolean running = true;
Scanner input = new Scanner(System.in);
generateWord();
System.out.println("You have " + LIVES + " lives to guess the word! \n" + guessWord);
while(running){
guessLetter(input.next().charAt(0));
if(guessWord == randWordExt){
running = false;
} else {
System.out.println(guessWord);
System.out.println("Lives left: " + LIVES);
}
}
input.close();
System.out.println("The word was " + randWord + ", you guessed it in " + " moves!");
}
The generateWord method:
public static void generateWord(){
randWord = WORD_LIST[(int)(Math.random() * 87)];
for(int i = 0; i < randWord.length(); i++){
guessWord = guessWord + "_ ";
}
for(int i = 0; i < randWord.length(); i++){
randWordExt = randWordExt + randWord.charAt(i) + " ";
}
}
And finally the guessLetter method:
public static void guessLetter(char letter){
boolean changed = false;
for(int i = 0; i < randWordExt.length(); i++){
if(!(guessWord.charAt(i) == letter)){
if(randWordExt.charAt(i) == letter){
guessWord = guessWord.substring(0, i) + letter + guessWord.substring(i + 1);
changed = true;
} else if (randWordExt.charAt(i) != letter && i == randWordExt.length() - 1 && changed == false){
LIVES -= 1;
System.out.println("\'" + letter + "\'" + " is not in the word!");
}
} else {
System.out.println("\'" + letter + "\'" + "has already been guessed!");
}
}
}