import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/**
* 猜字母小游戏
* @author 543363559@qq.com
* @date 2017年4月24日 下午8:38:33
*/
public class GuessLetter {
public static void main(String[] args) {
//控制台输入对象
Scanner sc = new Scanner(System.in);
System.out.println("欢迎进入猜字母游戏!");
System.out.println("请输入你猜的5大大写字母:");
//字符串
String s = sc.nextLine();
//将字符串直接转换为字符数组
char[] input = s.toCharArray();
//随机生成char
char[] outChar = getChar();
System.out.println("系统生成的为:" + Arrays.toString(outChar));
//比较
int answer[] = copare(input, outChar);
System.out.println("您猜对了" + answer[0] + "个");
System.out.println("有" + answer[1] + "个位置正确");
}
/**
*
* <br>方法说明:比较两个字符数组
* <br>输入参数:
* <br>返回类型:
*/
private static int[] copare(char[] input, char[] outChar) {
int[] answer = new int[2];
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < outChar.length; j++) {
if (input[i] == outChar[j]) { //字符相同
answer[0]++;
if (i == j) { //位置相同
answer[1]++;
}
}
}
}
return answer;
}
/**
*
* <br>方法说明:随机生成5个不重复字母
* <br>输入参数:
* <br>返回类型:char[]
*/
private static char[] getChar() {
char[] ch1={'A','B','C','D','E','F','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
Random r = new Random();
char[] ch2 = new char[5];
//flags对应ch1每一个位置的状态值,是否被取到
boolean[] flag = new boolean[ch1.length];
int index;
for(int i = 0; i < ch2.length; i++){
do{
index = r.nextInt(ch1.length);
}while(flag[index]);
ch2[i] = ch1[index];
flag[index] = true; //说明已用过ch[index]
}
return ch2;
}
}
猜字母小游戏
最新推荐文章于 2021-07-08 20:48:58 发布