Problem Description: Create an application that will play hangman. You do not ha
ID: 3767581 • Letter: P
Question
Problem Description: Create an application that will play hangman. You do not have to draw the hangman, just display the number of incorrect guesses on the screen. Allow the user to select from several categories. Display a list of underscores representing the phrase or word to be guessed. What the user guesses correctly, replace the appropriate underscores with the guessed letter. If the letter guessed is incorrect, then update the incorrect guess counter. Keep track of the user wins and losset Allow the user to continue to play the game. The phrases being guessed should not be input by the user. They could be "hard coded" into your program somehow.Explanation / Answer
public class Hangman
{
public static void main(String[] args)
{
String[] words = {"writer", "that", "program"};
int randomWordNumber = (int) (Math.random() * words.length);
char[] enteredLetters = new char[words[randomWordNumber].length()];
int triesCount = 0;
boolean wordIsGuessed = false;
do
{
switch (enterLetter(words[randomWordNumber], enteredLetters))
{
case 0:
triesCount++;
break;
case 1:
triesCount++;
break;
case 2:
break;
case 3:
wordIsGuessed = true;
break;
}
}
while (! wordIsGuessed);
System.out.println(" The word is " + words[randomWordNumber] +" You missed " + (triesCount -findEmptyPosition(enteredLetters)) +" time(s)");
}
public static int enterLetter(String word, char[] enteredLetters)
{
System.out.print("(Guess) Enter a letter in word ");
if (! printWord(word, enteredLetters))
return 3;
System.out.print(" > ");
Scanner input = new Scanner(System.in);
int emptyPosition = findEmptyPosition(enteredLetters);
char userInput = input.nextLine().charAt(0);
if (inEnteredLetters(userInput, enteredLetters))
{
System.out.println(userInput + " is already in the word");
return 2;
}
else if (word.contains(String.valueOf(userInput)))
{
enteredLetters[emptyPosition] = userInput;
return 1;
}
else
{
System.out.println(userInput + " is not in the word");
return 0;
}
}
public static boolean printWord(String word, char[] enteredLetters)
{
boolean asteriskPrinted = false;
for (int i = 0; i < word.length(); i++)
{
char letter = word.charAt(i);
if (inEnteredLetters(letter, enteredLetters))
System.out.print(letter);
else
{
System.out.print('*');
asteriskPrinted = true;
}
}
return asteriskPrinted;
}
public static boolean inEnteredLetters(char letter, char[] enteredLetters)
{
return indexOf(letter, enteredLetters) >= 0;
}
public static int findEmptyPosition(char[] enteredLetters)
{
return indexOf('u0000', enteredLetters)
}
public static int indexOf(char ch, char[] vals)
{
return Arrays.asList(vals).indexOf(Character.valueOf(ch));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.