标签:判断 buffer acea input boolean ash class dom har
游戏规则:猜4个不重复的数字(0-9),猜对数字并且位置正确记为A,猜对数字但位置不对记为B
首先定义全局常量
// 数字总数 public static final int NUMBER_SIZE = 4; // 几次机会 public static final int GUESS_TIMES = 10;
生成随机答案
public static String getRandomNumber() { StringBuffer sb = new StringBuffer(); Random ran = new Random(); for (int i = 0; i < NUMBER_SIZE; i++) { sb.append(ran.nextInt(10)); } return sb.toString(); }
随机答案和用户输入都有可能不正确,需要一个校验方法校验数字是否合法
public static boolean validate(String data) { if (data.length() != NUMBER_SIZE) { return false; } // 用set判断是否有重复数字 Set<Character> set = new HashSet<>(); for (int i = 0; i < data.length(); i++) { char ch = data.charAt(i); if (ch >= 48 && ch <= 57) { set.add(ch); } else { return false; } } return set.size() == NUMBER_SIZE; }
写一个判断用户输入对错的方法
public static String judge(String rightNumber, String guessNumber) { // 预处理正确结果,数值为key,位置为value Map<Character, Integer> map = new HashMap<>(); char[] rightArr = rightNumber.toCharArray(); for (int i = 0; i < rightArr.length; i++) { map.put(rightArr[i], i + 1); } // 值对,位置也对 int A = 0; // 值对,位置不对 int B = 0; // 判断输入 char[] guessArr = guessNumber.toCharArray(); for (int i = 0; i < guessArr.length; i++) { char value = guessArr[i]; if (map.containsKey(value)) { if (map.get(value) == i + 1) { A++; } else { B++; } }
} return A + "A" + B + "B"; }
开始一局游戏
public static void startOneRound() { String rightNumber = ""; // 生成随机答案 while (true) { rightNumber = getRandomNumber(); if (validate(rightNumber)) { break; } } System.out.println("猜数字游戏规则:猜4个不重复的数字(0-9),猜对数字并且位置正确记为A,猜对数字但位置不对记为B,一共有" + GUESS_TIMES + "次机会."); System.out.println("游戏开始,请输入答案按回车确认"); int times = 0; Scanner scanner = new Scanner(System.in); while (true) { String input = scanner.nextLine(); // 容错用户输入 input = input.replaceAll(" ", ""); boolean available = validate(input); if (available) { times++; String judgeStr = judge(rightNumber, input); if (judgeStr.equals("4A0B")) { System.out.println("恭喜你,回答正确!"); break; } if (times >= GUESS_TIMES) { System.out.println("次数用尽,下次继续努力,正确答案:" + rightNumber); break; } System.out.println(judgeStr + ",第" + times + "次,还有" + (GUESS_TIMES - times) + "次机会"); } else { // 输入错误的数据说明用户不清楚规则,不占用次数 System.out.println("请输入正确的数字"); } } scanner.close(); }
用main方法启动
public static void main(String[] args) { startOneRound(); }
over
标签:判断 buffer acea input boolean ash class dom har
原文地址:http://www.cnblogs.com/koalaGo/p/6726660.html