编写一个猜字游戏。随机产生一个单词,提示用户一次猜测一个字母。单词中的每个字母显示为一个星号。当用户猜测正确后,正确的字母显示出来。当用户猜出一个单词,显示猜错的次数,并且询问用户是否继续对另外一个单词进行游戏。声明一个数组来存储单词。如下所示:
String[] words = {"write", "that", ...};
package pack2;
import java.util.Scanner;
public class GuessWord {
public static void main(String[] args) {
guessWord();
}
/**猜字游戏*/
public static void guessWord() {
try(Scanner input = new Scanner(System.in);) {
//存储单词数组
String[] words = {"write", "listen", "recite", "dictation", "look",
"read", "program"};
int count = 0; //计数猜错次数
char tag;
//外层循环执行新单词的循环
do { //随机待猜单词
String guessWord = words[(int)(Math.random() * words.length)];
StringBuffer word = new StringBuffer(guessWord.length()); //已猜单词
count = 0; //每次循环重置count
for (int i = 0; i < word.capacity(); i++)
word.append('*'); //初始为 '*'号
//内层循环执行特定单词的循环,当(已猜单词 == 随机待猜单词)时退出循环
while(!word.toString().equals(guessWord)) {
System.out.print("(Guess) Enter a letter in word "+word+" > ");
char guess = input.next().charAt(0);
int index = index(guess, guessWord, word); //获取下标
if(index != -1 && index != -2) //非负下标时替换字符
word.replace(index, index + 1, String.valueOf(guess));
else {
if(index == -1) count++; //存在错误单词时count++
System.out.println("\t"+guess+" is "+(index == -1 ? "not" :
"already")+" in the word");
}
}
System.out.println("The word is "+word+". You missed "+count+" time"+
(count > 1 ? "s" : ""));
System.out.print("Do you want to guess another word? Enter y or n> ");
tag = input.next().charAt(0);
System.out.println();
}while(tag == 'Y' || tag == 'y');
}
}
/**获取特定字符下标*/
public static int index(char c, String string, StringBuffer word) {
int count = 0; //字符数
for (int i = 0; i < string.length(); i++) {
//存在字符c时,count++
if(c == string.charAt(i)) count++;
//如果存在字符c且指定下标不为c,返回下标
if(c == string.charAt(i) && word.charAt(i) != c)
return i;
else continue; //否则,结束本次循环
}
//count >= 1 表明字符已存在,否则不存在
return count >= 1 ? -2 : -1;
}
}