本文主要是介绍java10: 猜字母,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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] + "位置");}
}
这篇关于java10: 猜字母的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!