Java、猜字游戏

编写一个猜字游戏。随机产生一个单词,提示用户一次猜测一个字母。单词中的每个字母显示为一个星号。当用户猜测正确后,正确的字母显示出来。当用户猜出一个单词,显示猜错的次数,并且询问用户是否继续对另外一个单词进行游戏。声明一个数组来存储单词。如下所示:

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;
	}
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值