猜词游戏

来源:互联网 发布:查看mysql启动状态 编辑:程序博客网 时间:2024/06/10 22:15

(猜词游戏)编写一个猜词游戏。随机产生一个单词,提升用户一次猜测一个字母。单词中的每个字母显示为一个星号。当用户猜测正确后,正确的字母显示出来。

当用户猜出一个单词,显示猜错的次数,并询问用户是否继续对另外一个单词进行游戏。声名一个数组来存储单词,贴出代码如下:


import java.util.Random;
import java.util.Scanner;


public class test42 {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//想要随机的单词
String[] words = {"write","that","public","private","program"};
char c;
do{
    play(words);
    System.out.println("Do you want to guess anther word? Enter y or n:");

}while((c=input.next().charAt(0))=='y');//这句判断输入的y就继续玩,其他就结束
                                       //这样写比较简洁直观


}
//开始玩猜字游戏
public static void play(String[] words){
Scanner input = new Scanner(System.in);
int miss = 0; //记录你猜错的次数
char c;       //存你每次输入的单词
Random random = new Random(); //利用Randow对象 随机一个单词
int i = random.nextInt(words.length);
//用一个char数组,长度为单词的长度,并把里面的值全部赋值为*
char[] ch = new char[words[i].length()];
for (int j = 0; j < words[i].length(); j++) {
ch[j]='*';
}
//System.out.println(words[i]);
do{
System.out.print("(Guess) Enter a letter in word ");
System.out.print(ch);System.out.println(" >");
c = input.next().charAt(0);//存入字母
//判断字母在单词里是否出现,如果没有则miss+1;
if(words[i].indexOf(c)==-1){
System.out.println(c+" is not in the word");
miss++;
}
//判断字母是不是已经猜过了。
for (int j = 0; j < ch.length; j++) {
if(ch[j]==c)System.out.println(c+" is alerady in the word ");;
break;
}


}while(guessWord(words[i],ch,c));//将你猜对的字母显示出来,并且判断
                                //如果一个*都没有说明已经全部猜出,结束本次游戏

System.out.println("The word is "+words[i]+" You miss "+miss+" time");

}


public static boolean guessWord(String str,char[] ch,char c){

for (int i = 0; i < str.length(); i++) {//将猜对的字母显示在相应的位置
if(str.charAt(i)==c)ch[i]=c;
}
for (int i = 0; i < str.length(); i++) {
if(ch[i]=='*') return true;
}
return false;
}


}