1. Write a hangman’s program where the user is a computer that has to guess the
ID: 3834836 • Letter: 1
Question
1. Write a hangman’s program where the user is a computer that has to guess the word “JAVA.” The computer uses a brute force method. a. First write the program that shows (prints) each guess (the letter) and also draws the result (line by line, circle by circle) when the guess is wrong. b. What does the brute force method do exactly?
Word List:
ADA
COBOL
LOGO
PEARL
BASIC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Make sure the computer is playing against the user. The user picks the word. Thanks chief.
Explanation / Answer
Hangman's program code is given below :
import java.util.Random;
import java.util.Scanner;
public class HangMan3 {
public static char[] star;
public static void main (String args[])
{
String secretWord = userInput.next();
int len = secretWord.length(); //Store the length which will be used to see if puzzle was solved.
char[] temp = new char[len]; //Store a temp array which will be displayed to the user
for(int i = 0; i < temp.length; i++) //initialize the array
{
temp[i] = '*';
}
System.out.print(" ");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println(" Attempts left: " + attempts);
System.out.print("Enter letter: ");
String test = userInput.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
//Find matches
int foundPos = -2;
int foundCount = 0; //How many matches did we find
while((foundPos = secretWord.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar; //Update the temp array from * to the correct character
foundCount++;
len--; //Decrease overall counter
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
//Print
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println(" ---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println(" ---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was "" + secretWord + """);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.