The following is only part of my code. Im having an issue in my hangman game where the "hanging" method doesn't seem to be working. For example if the word to guess was 'banana' and you guess 'a' the word would then appear as 'a_a_a' but instead what I'm getting is just '_____'. Using system.out.print I found out that at the end of the hanging method 'word' does actually equal '_a_a_a' but when it prints again in the main method it goes back to just underscores. Anyone sure why this is happening?
public class Hangman
{
private static int lives = 7;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Player 1, please enter a word.");
String str = sc.nextLine();
String word = UnderscoreWord(str);
char[] ar = word.toCharArray();
while(lives > 0)
{
System.out.println("Player 2, please guess a letter");
System.out.println(word);
char guess = sc.next(".").charAt(0);
hanging(guess, word, ar, str);
}
sc.close();
}
public static void hanging(char guess, String word, char ar[], String str)
{
String newWord = "";
for(int i = 0; i < word.length(); i++)
{
if(str.charAt(i) == guess)
{
ar[i] = guess;
newWord += ar[i];
}
else if(word.charAt(i) != '_')
{
newWord += str.charAt(i);
}
else
{
newWord += "_";
}
}
if (word.equals(newWord))
{
System.out.println("Wrong!");
lives--;
alive(lives);
}
else
{
word = newWord;
}
if (word.equals(str))
{
System.out.println("You win!");
}
}
public static String UnderscoreWord(String str)
{
String underscore = new String("");
int length = str.length();
for(int i = 0; i < length; i++)
{
underscore += "_";
}
return underscore;
}
}