package org.blackice.test; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class GuestNumber { /** * @param args */ public static void main(String[] args) { try{ int i = 0; int iLost = 0; String sNum = "0000"; System.out.println("=============================================="); System.out.println("指令说明:"); System.out.println("0、输入 start 重新开始游戏并查看答案"); System.out.println("1、输入 redo 重新开始游戏并查看答案"); System.out.println("2、输入 exit 退出游戏"); System.out.println("游戏规则"); System.out.println("1、游戏开始时系统自动产生一个随机数"); System.out.println("2、系统接收您输入的四位数字,并加以比较,猜中的数字位以 1 表示"); System.out.println("=============================================="); String inputStr = ""; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); do{ inputStr = br.readLine(); //重新开始 if(inputStr.equals("redo")){ i=0; sNum = CreateNum(); System.out.println("答案是:" + sNum); }else if(inputStr.equals("exit")){ System.exit(0); }else if(inputStr.equals("start")){ i=0; sNum = CreateNum(); }else{ if((!inputStr.matches("[0-9]+"))||inputStr.length()>4||inputStr.length()<4){ System.out.println("输入错误,请输入四位数字" + inputStr.length()); }else{ i++; if(inputStr.equals(sNum)){ System.out.println("恭喜您猜中数字!剩余次数:" + (10-i)); }else{ if(i>=10){ System.out.println("很遗憾,您未猜中,正确答案为:" + sNum); }else{ System.out.println("本次对比结果:" + CompareNum(inputStr,sNum)); System.out.println("您还有" + (10-i) + "次机会"); } } } } } while(inputStr!=null); }catch(Exception e){ System.out.println(e.getMessage()); } } //比较两个数,并返回比较结果 private static String CompareNum(String str1,String str2){ String strTemp = ""; String v1 = "",v2=""; for(int i=1;i<=4;i++){ v1 = str1.substring(i-1,i); v2 = str2.substring(i-1,i); if(v1.equals(v2)){ strTemp += "1"; }else{ strTemp += "0"; } } return strTemp; } //取得一个随机数 private static String CreateNum(){ String strTemp = ""; Random rd = new Random(); strTemp = Math.abs(rd.nextInt()) + ""; strTemp = strTemp.substring(1, 5); return strTemp; } }