Write a reverse Hangman game in which the user thinks of a word and the computer
ID: 3762150 • Letter: W
Question
Write a reverse Hangman game in which the user thinks of a word and the computer tries to guess the letters in that word. Your program must output what the computer guessed on each turn, and show the partially completed word. It also must use pseudorandom functions to make guesses. That is, it should not simply try all the letters in order, nor should it use the user’s input to its advantage. A sample run of your program might be as follows:
>>Please enter a word for me to guess(letters only): >>hello >>My guess: n current status: _____ >>My guess: l current status: __ll_ >>My guess: x current status: __ll_ >>My guess: o current status: __llo
(java)
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
public class Hangman {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a word(letters only): ");
String word = input.nextLine();
Random generator = new Random(System.currentTimeMillis());
char ch;
int filled = 0;
StringBuilder ans = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
ans.append('_');
}
while (filled != word.length()) {
ch = (char) (generator.nextInt(26) + 'a');
System.out.print("My guess:"+ch+" ");
int index = word.indexOf(ch);
while (index >= 0) {
if(ans.charAt(index)=='_')
{
filled++;
}
ans.setCharAt(index, ch);
index = word.indexOf(ch, index + 1);
}
System.out.println("Current status: "+ans.toString());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.