【java】猜字游戏

猜字游戏

首先声明一个字符数组来储存单词(由程序设计者决定储存哪些单词及个数),根据储存的下标来随机访问其中一个,作为一次猜字。
进入猜字流程的入口。设置一个字符变量entrance,初始化为‘y’,当一次猜字结束时,让用户输入‘y’或者‘n’以确定是否继续。对滴,判断的条件就是entrance是否为‘y’。
接下来考虑一次猜字的具体流程了。
获得谜底单词,然后确定它的长度(lenth)。
嗯……关于如何显示,还要构造一个方法。我想使用散列(hash),声明数组hashTable[26],初始化为0。用下标来表示字母(小写),其中内容代表是否在单词中出现(1为出现过,0表示未出现过,2为被用户猜中了)。
脑子有点乱,就先把所有想到的列出来吧。
获得用户输入的字母后,若在单词中出现了,变*为该字母,若没出现则输出该字母不在单词中,或者该字母之前已经输入过了则输出该字母已经在单词中了。
有二,一个是记录逐步用户输入的正确的字母,二是一个转化显示的过程/方法。

总结梳理如下,
1.获取谜底单词,用hashTable记录其中出现的字母(hashTable[i]置为1),若hashTable[i]为2则打印字符‘i’,否则在i出现的位置打印‘*’
2.获得用户输入的字符j,若hashTable[j]为1则将其自增为2(并将计数器++),若hashTable[j]为0则输出“j is already in the word”,若hashTable[j]为0则输出“j is not in the word”。
3.控制本次猜字结束的条件:计数器==单词长度
4.控制猜字游戏结束的条件是:entrance!=y
大体就这样了。
现在来看看会用到几个方法吧。
1)谜底单词产生器
暂时就这样了。。。

嗯…………最后终于写出来了哒!
不过代码和预期的长得不太一样,更别扭一些。为什么呢?一个是因为这次的程序设计在逻辑上结构更复杂一些,另一个是因为思路还不够清楚的时候就着急着写代码了。
回过头来看自己的代码,我发现数组hashTable之作用比我预期的大,通过它程序完成了诸多判断,也简化了我的思路。
运行结果:
在这里插入图片描述

千言万语,都付代码中。完整代码:

import java.util.Scanner;

public class GuessTheWord {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		String[] words = {"life", "is", "simple", "you",
				"make", "choices", "and", "you",
				"do", "not", "look", "back"
				};
		
		char entrance = 'y';
		while(entrance == 'y') {
			int[] hashTable = new int[26];
			String answer = answerToTheRiddle(words);
			int lenth = answer.length();
			for(int i = 0; i < lenth; i++) {
				hashTable[answer.charAt(i) - 'a'] = 1;
			}
			
			int number = 0;
			int miss = 0;
			while(number != lenth) {
				System.out.print("(Guess) Enter a letter in word ");
				for(int i = 0; i < lenth; i++) {
					if(hashTable[answer.charAt(i) - 'a'] == 2)
						System.out.printf("%c", answer.charAt(i));
					else
						System.out.printf("*");
				}
				System.out.printf(">");
				String guess_string = input.next();
				char guess = guess_string.charAt(0);
				
				if(hashTable[guess - 'a'] == 0) {
					System.out.printf("	%c is not in the word\n", guess);
					miss++;
				}
				else if(hashTable[guess - 'a'] == 1) {
					hashTable[guess - 'a'] = 2;
					number++;
				}
				else
					System.out.printf("	%c is already in the word\n", guess);
			}
			System.out.printf("The word is %s. You missed %d time\n", answer, miss);
			System.out.print("Do you want to guess another word? Enter y or n>");
			String entrance_string = input.next();
			entrance = entrance_string.charAt(0);
		};
		System.out.println("Let`s guess another word next time!");
	}
	
	public static String answerToTheRiddle(String[] words) {
		int index = (int)(Math.random() * 12);
		return words[index];
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42313005/article/details/83216304
今日推荐