java语言程序设计第十版(Introduce to java 10th) 课后习题 chapter7-33
自己纯手工,欢迎讨论
package chapter7;
import java.util.Scanner;
public class T35 {
static int num = 0;// 猜对字母计数器
static int number = 0;// 猜词次数计数器
public static void main(String[] args) {
String[] words = { "write", "hangman", "game", "that", "randomly", "generates", "word" };
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
do {
String choice = words[(int) (Math.random() * 7)];
// 单词存到数组里
char[] word = new char[choice.length()];
for (int i = 0; i < choice.length(); i++)
word[i] = choice.charAt(i);
char[] caiWord = new char[choice.length()];
for (int i = 0; i < choice.length(); i++)
caiWord[i] = '*';
while (num != choice.length()) {
print(caiWord);
caiWord = caiCi(caiWord, word, in.next().charAt(0));
}
printRight(caiWord);
} while (in.next().charAt(0) == 'y');
}
public static void print(char[] k) {
System.out.print("(Guess) Enter a letter in word ");
System.out.print(k);
System.out.print(" > ");
}
public static void printRight(char[] k) {
System.out.print("The word is ");
System.out.print(k);
if ((number - num == 1) || (number - num == 0))
System.out.printf(" .You missed %d time\n", (number - num));
else
System.out.printf(" .You missed %d times\n", (number - num));
System.out.print("Do you want to guess another word? Enter y or n>");
}
public static char[] caiCi(char[] n, char[] k, char c) {
number++;
for (int i = 0; i < k.length; i++) {
if (c == k[i]) {
n[i] = c;
}
}
int numRight = 0;
for (int i = 0; i < n.length; i++) {
if (n[i] != '*')
numRight++;
}
num = numRight;
return n;
}
}