题目: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 finishes a word,display the number of misses and ask the user whether to continue for another word.Declare an array to store words,as follows:
String[] word = {"write","that",...};
题目来源:
题目选自《JAVA程序语言设计》 P341-9.31***
代码如下:
import java.util.Scanner;
public class HangmanDemo {
Scanner input = new Scanner(System.in);
private String[] words = { "write", "that", "program", "problem",
"yourself" };
public HangmanDemo() {
while (true) {
int num = (int) (Math.random() * 5);
String str = words[num];
int n = Guess(str);
System.out.println("The word is " + str + ". You missed " + n
+ " time.\n");
System.out
.print("Do you want to guess for another word? Enter y or n>");
String s = input.next();
if (s.equals("n"))
break;
}
System.out.println("Game over!");
}
int Guess(String str) {
int count = 0, number = str.length();
char[] a = new char[number];
for (int i = 0; i < number; i++) {
a[i] = '*';
}
while (true) {
System.out.print("(Guess) Enter a letter in word ");
for (int i = 0; i < str.length(); i++) {
System.out.print(a[i]);
}
System.out.print(" > ");
String letter = input.next();
int m = 0;
for (int i = 0; i < str.length(); i++) {
if (a[i] == letter.charAt(0)) {
System.out.println(" " + letter
+ " is already in the word");
m=1;
} else if (str.charAt(i) == letter.charAt(0)) {
a[i] = letter.charAt(0);
number--;
m = 1;
}
}
if (m == 0) {
System.out.println("\t" + letter + " is no in the word");
count++;
}
if (number == 0)
break;
}
return count;
}
public static void main(String[] args) {
new HangmanDemo();
}
}
运行结果:
(Guess) Enter a letter in word ******* > p
(Guess) Enter a letter in word p****** > s
s is no in the word
(Guess) Enter a letter in word p****** > r
(Guess) Enter a letter in word pr***** > p
p is already in the word
(Guess) Enter a letter in word pr***** > m
(Guess) Enter a letter in word pr****m > o
(Guess) Enter a letter in word pro***m > b
(Guess) Enter a letter in word prob**m > l
(Guess) Enter a letter in word probl*m > e
The word is problem. You missed 1 time.
Do you want to guess for another word? Enter y or n>n