public class guessword {
public static void main(String[] args) {
String[] words = {"apple","banana","cherry","orange","pear","watermelon","pitaya","mango","coconut"};
//定义数组为题库
Random random = new Random();
int windex = random.nextInt(words.length);
//产生随机数组下标
String guessword = words[windex];
//产生被猜的单词
System.out.println(guessword);
//输出被猜写的单词
String[] word = new String[words[windex].length()];
//把被猜写的单词转成字符串数组
for (int i = 0; i <word.length;i++){
word[i] = "-";
}
//遍历数组,把数组中的字符串替换成等长度的“-”
for (int i = 0; i < word.length;i++){
System.out.print( word[i]+" ");
}
//输出与被猜写单词等长度的“-”
int guesscount = 5;
//设置猜单词次数
System.out.println();
//换行
while (true){
Scanner scanner = new Scanner(System.in);
String zm = scanner.next();
//接受用户输出字母
int num = 0;
if (guessword.indexOf(zm) >= 0){
while (true){
num = guessword.indexOf(zm,num);
//定义 输入字母 在被猜写单词中的 起始 查找下标
if (num >= 0){
word[num] = zm;
num++;
//找到并替换“-”
}
else {
break;
}
}
for (int i = 0; i < word.length;i++){
System.out.print( word[i]+" ");
//输出当前查找情况
}
System.out.println();
//换行
}else {
guesscount--; // 输入的字母不在被猜单词内,猜单词次数减一
if (guesscount == 0){
System.out.println("你输了,游戏结束"); //如果猜单词次数等于0 游戏结束 你输了 跳出循环
break;
}
System.out.println("错了,还有"+guesscount+"次错的机会"); //输出剩余猜单词次数
}
boolean isfind = false; //布尔变量 判断 被猜写单词中是否还存在“-”
for (int i = 0; i < word.length;i++){
if (word[i].equals("-")){
isfind = true; // 如果还存在继续猜
break;
}
}
if (isfind == false){
System.out.println("你赢了"); //如果不存在 游戏结束 你赢了
}
}
}
}
网友评论