public class ClassHomeWork01 {
public static void main(String[] args) {
char[] chars = generate();
char[] input = new char[5];
int[] result = new int[2];
int count = 0;
System.out.println(chars);//shown answer
System.out.println("请输入所猜的五个字符");
while (true){
Scanner scanner = new Scanner(System.in);
String inputStr = scanner.next().toUpperCase().trim();
if (inputStr.equalsIgnoreCase("exit")){
System.out.println("see u next time");
break;
}
input = inputStr.toCharArray();
result = check(chars,input);
if (result[0] == chars.length){
int score = 100 * chars.length - 10 * count;
System.out.println("猜对了,分数为:"+score+",游戏次数为:"+count);
break;
}else {
count++;
System.out.println("字符对个数:"+result[0]+",位置对个数:"+result[1]+",游戏次数:"+count+
"若想退出请输入:exit");
}
}
}
public static char[] generate(){
String chsStr = "";
for (char c = 'A'; c <= 'Z'; c++){
chsStr += c;
}
char[] letters = chsStr.toCharArray();
// System.out.println(letters);
boolean[] flags = new boolean[letters.length];
char[] chars = new char[5];
for (int i = 0; i < chars.length; i++){
int index;
do {
index = (int) (Math.random()*(letters.length));
}while (flags[index]);
chars[i] = letters[index];
flags[index] = true;
}
return chars;
}
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]){
result[1]++;
if (i==j){
result[0]++;
}
}
}
}
return result;
}
}
[算法系列] 猜字符游戏(Java)
最新推荐文章于 2024-08-19 11:12:00 发布