package day10; import java.util.Random; import java.util.Scanner; public class Demo01 { public static void main(String[] args) { char[] answer; char[] input; int[] result; int count = 0; System.out.println("\t欢迎 欢迎"); answer = generate(5); System.out.println(answer); while (true) { input = userInput(); count++; result = check(answer, input); show(count, result); if (result[0] == 5 && result[1] == 5) { break; } } } public static char[] generate(int n) { char[] chs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; boolean[] used = new boolean[chs.length]; int i; char[] answer = new char[n]; int index = 0; Random random = new Random(); do { i = random.nextInt(chs.length); if (used[i]) continue; answer[index++] = chs[i]; used[i] = true; } while (index != n); return answer; } public static char[] userInput() { Scanner con = new Scanner(System.in); char[] input = {}; do { System.out.print("输入:"); String str = con.nextLine(); input = str.toCharArray();// 将 字符串 转换为数组 } while (input.length != 5); return input; } public static int[] check(char[] answer, char[] input) { int[] result = {0,0}; for (int i = 0; i < answer.length; i++) { for (int j = 0; j < input.length; j++) { if (answer[i] == input[j]) { result[0]++; if (i == j) result[1]++; break; } } } return result; } public static void show(int count, int[] result) { if (result[0] == 5 && result[1] == 5) { System.out.println(count + "次,就全部猜对啦"); return; } System.out.println(count + "次,猜对" + result[0] + "个字母" + "猜对" + result[1] + "位置"); } }