*(Please answer all parts of this question; A, B, C and D)* In Java Programming,
ID: 3695803 • Letter: #
Question
*(Please answer all parts of this question; A, B, C and D)*
In Java Programming,
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?
Also, the computer draws both the gallows and the victim. The gallows and hapless victim look like this:
C. Why does the computer win every time if the word is JAVA?
D. Look at the following list of words and determine ahead of time if the computer would win. Then prove your conclusion by running your program.
Word List:
ADA
COBOL
LOGO
PEARL
BASIC
oo@Explanation / Answer
1.
import java.util.Scanner;
import java.io.*;
public class lhangman
{
public static void main(string[] args) throws IOException
{
Scanner lscan = new Scanner (System.in);
char lAgain = 'n';
String lsecret;
StringBuffer ldashes;
final int lMAXPARTS =6;
int lbodyparts;
boolean done;
String lguess;
String guesses;
char lLetter;
Scanner lInfile = new Scanner (new FileReader("hangWords.txt"));
do
{
lsecret = lInfile.next();
guesses = " ";
done = false;
lbodyparts = lMAXPARTS;
ldashes = lmakeDashes(lsecret);
While (! done)
{
System.out.println("Your word is here: " + ldashes);
System.out.println("Guesses : " + guesses);
System.out.print("Enter a guess : ");
lguess=lscan.next();
if (lguess.length () > 1)
{
if(lguess.equals(lsecret))
System.out.println("You win!");
else
System.out.println("You lose");
done=true;
}
else
{
lLetter = lguess.charAt(0);
guesses += lLetter;
if (lsecret.indexOf (lLetter) < 0)
{
- -lbodyparts;
System.out.print("bad guess - ");
}
else
{
lmatchLetter(lsecret,ldashes,lLetter);
}
System.out.println(lbodyparts + "bodyparts left");
if(lbodyparts == 0)
{
System.out.println("You lose");
done= true;
}
if (lsecret.equals(ldashes.toString() ) )
{
System.out.println("You win! ");
done= true;
}
}
}
if (lInfile.hasNext() )
{
System.out.print("play again ?: ");
lAgain = lscan.next().charAt(0);
}
else
System.out.println("Thanks ");
}
while (lInfile.hasNext() && (lAgain == 'Y' // lAgain == 'Y') );
}
public static void lmatchLetter(String lsecret,StringBuffer ldashes,char lLetter)
{
for (int lIndex = 0; lIndex < lsecret.length(); lIndex++)
if (lsecret.charAt(lIndex) == lLetter)
ldashes.setCharAt(lIndex,lLetter);
System.out.print("good guess - ");
}
public static StringBuffer lmakeDashes(String s)
{
StringBuffer ldashes = new StringBuffer (s.length());
for (int lcount = 0; lcount < s.length(); lcount++)
ldashes.append ( ' -');
return ldashes;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.