Game: Hangman Write a hangman game that randomly generates a word and prompts th
ID: 3882302 • Letter: G
Question
Game: Hangman Write a hangman game that randomly generates a word and prompts the user to guess one letter at a time, as shown in the sample run. Each letter in the word is displayed as an asterisk. When the user makes a correct guess, the actual letter is then displayed. When the user finishes a word, display the number of misses and ask the user whether to continue to play with another word. Declare an array to store words, as follows: // Add any words you wish in this array String[] words {"write", "that", ); (Guess) Enter a letter in wordp Enter (Guess) Enter a letter in word pr**t** > p-Enter p is already in the word (Guess) Enter a letter in word pr****oEnter (Guess) Enter a letter in word pro***g Enter (Guess) Enter a letter in word progr** nEnter n is not in the word (Guess) Enter a letter in word progr**m Enter (Guess) Enter a letter in word progr*m a Ente The word is program. You missed 1 time Do you want to guess another word? Enter y or n>Explanation / Answer
import java.math.*;
import java.util.*;
public class WordGame
{
public static void main(String s[])
{
String[] words ={"write","that","program"};
int t = words.length;
String w;
int x,y,miss;
Scanner sc= new Scanner(System.in);
char l,c='y';
while(c=='y')
{
x=(int)(Math.random()*(t));
w=words[x];
char[] chars = w.toCharArray();
char[] hidden = new char[w.length()] ;
for(int i=0;i<hidden.length;i++)
{
hidden[i]='*';
}
boolean z=false;
int count =0;
miss =0;
while(!z)
{
System.out.print("(Guess) Enter a letter in word "+new String(hidden));
l=sc.next().charAt(0);
y=0;
for(int i=0;i<hidden.length;i++)
{
if(chars[i]==l)
{
y++;
if(hidden[i]=='*')
{
hidden[i]=l;
count ++;
y++;
}
}
}
if(y==1) System.out.println(l+" already present") ;
else if(y==0)
{
miss++;
System.out.println(l+" not present");
}
if(count == hidden.length) z=true;
}
System.out.println("The word is "+w+" You missed "+miss+" times" );
System.out.println("Do you want to guess another word y or n ");
c=sc.next().charAt(0);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.