2014-12-09
17:42:20
系统给定一个四位数。您有5次猜数机会,每次您可输入一个四位数,系统判断后会给出一个字符串,字符串由T、F、C表示。T表示该位上的数字是正确的;C表示该位上的数字存在这个四位数中,但位置错误;F表示该位上的数字是错误的,即不存在这个四位数中。
程序代码如下:
1 /** 2 * @author nlee 3 * @version 2:58:11 PM Dec 9, 2014 4 */ 5 package guessNum; 6 7 import java.util.Scanner; 8 9 public class GuessNum10 {11 public static void main(String[] args)12 {13 // 1.生成正确答案14 String correctAnswer = "";15 // 生成四个一位随机数,并将其转换成String类型16 for (int i = 0; i < 4; i++)17 {18 int a = (int) (Math.random() * 10);19 correctAnswer += a;20 }21 // System.out.PRintln(correctAnswer);22 23 Scanner in = new Scanner(System.in);24 // 输入上限为5次25 int times = 5;26 for (int j = 0; j < times; j++)27 {28 System.out.println("You have " + (times - j) + " times, "29 + "please entry your number(four figures):");30 // 2.输入猜测的数字31 String num = in.next();32 // num与correctAnswer的比较结果33 String implynum = "";34 // 3.比较num与correctAnswer35 for (int i = 0; i < 4; i++)36 {37 if (correctAnswer.charAt(i) == num.charAt(i))38 {39 implynum += "T";40 }41 else42 // 判断correctAnswer是否包含num.charAt(i)这个数字43 if (correctAnswer.contains(((CharSequence) ("" + num44 .charAt(i)))))45 {46 implynum += "C";47 }48 else49 {50 implynum += "F";51 }52 }53 System.out.println(implynum);54 // 如果implynum等于“TTTT”,表明猜对了,结束循环55 if (implynum.equals("TTTT"))56 {57 System.out58 .println("/nCorrect Answer!/nCongratulations!/nYou have succeed!");59 break;60 }61 else62 // 如果implynum不等于“TTTT”, 并且猜测次数也达到上限,表明游戏失败63 if (j == (times - 1))64 {65 System.out.println("/nYou have failed!/nGame over!");66 System.out.println("/nCorrect Answer is: " + correctAnswer);67 }68 else69 {70 System.out.println("Wrong Answer!/nPlease try again!/n");71 }72 }73 }74 }
新闻热点
疑难解答