java基础之猜字符小游戏

游戏目的:系统随机生成五个不重复的字符,用户输入自己所猜想的字符,回车提交答案之后返回结果:猜对的字符个数和猜对的字符位置个数,最后答对返回所得分数

项目分析:设计数据结构+设计算法

一:设计数据结构(设计变量):

整个游戏涉及的变量:

1):系统随机生成的字符:(相同类型且逻辑相同,故选择字符数组)char [] chs;

2)  :用户输入的字符 char  [] input;

3):返回的字符对个数和位置对个数 int result[];

4):返回所得分数int score

二:设计算法

1.设计方法:通过分析,我们按功能封装成方法,主方法不可少


public static void main(String[] args) {}
public static char[] genreate(){
//...
char[] chs = new char[5];
return chs;
}

public static int[] check(char[] chs,char[] input){
//...
int[] result = new int[2];
return result;
}

2.设计算法

比较方法:

public static int[] check(char[] chs,char[] input) {
		int[] result=new int[2];
		for(int i=0;i<chs.length;i++) {
			for(int j=0;j<input.length;j++) {
				if(chs[i]==input[j]) {
					//字符正确,对应的字符对个数增1
					result[1]++;
					if(i==j) {
						//对应位置也增1
						result[0]++;
					}
					break;
					
				}
			}
			
		}
		return result;
	}

3.最后我们在设计程序时,注意进行单元测试,方便以后的项目整合

public static void main(String[] args) {
		//对比较方法进行测试
		char [] chs = {'A','B','C','D','E'};
		char[] input = {'S','F','C','E','G'};
		int[] result=check(chs,input);
		System.out.println(result[1]+","+result[0]);
	}
最后我们输出结果,和我们预想的一样就,证明编写的方法正确


猜你喜欢

转载自blog.csdn.net/qq_34800258/article/details/80976202