<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
version1.0: http://www.cnblogs.com/Coder816/p/4153816.html
在1.0的版本中,系统生成的正确答案中有时候会出现相同的数字,这样在5次机会下,有可能无法猜中正确答案,游戏会显得很不合理。因此在1.1的版本中,将相应的代码改成了如下所示:
// 1.生成正确答案
String correctAnswer = "";
// 生成四个一位随机数,并将其转换成String类型
for (int i = 0; i < 4; i++)
{
int a;
// 如果数字a已经存在correctAnswer中,则重新生成一个数
do
{
a = (int) (Math.random() * 10);
}
while (correctAnswer.contains(((CharSequence) ("" + a))));
correctAnswer += a;
}
// System.out.println(correctAnswer);
同时,也包装了输入流,如下所示:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 2.输入猜测的数字
String num = "";
try
{
num = br.readLine();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
修改后的完整代码如下:
/*
@author nlee @version 2:58:11 PM Dec 9, 2014
/
package guessNum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GuessNum
{
public static void main(String[] args)
{
// 1.生成正确答案
String correctAnswer = "";
// 生成四个一位随机数,并将其转换成String类型
for (int i = 0; i < 4; i++)
{
int a;
// 如果数字a已经存在correctAnswer中,则重新生成一个数
do
{
a = (int) (Math.random() * 10);
}
while (correctAnswer.contains(((CharSequence) ("" + a))));
correctAnswer += a;
}
// System.out.println(correctAnswer);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 输入上限为5次
int times = 5;
for (int j = 0; j < times; j++)
{
System.out.println("You have " + (times - j) + " times, "
+ "please entry your number(four figures):");
// 2.输入猜测的数字
String num = "";
try
{
num = br.readLine();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// num与correctAnswer的比较结果
String implynum = "";
// 3.比较num与correctAnswer
for (int i = 0; i < 4; i++)
{
if (correctAnswer.charAt(i) == num.charAt(i))
{
implynum += "T";
}
else
// 判断correctAnswer是否包含num.charAt(i)这个数字
if (correctAnswer.contains(((CharSequence) ("" + num
.charAt(i)))))
{
implynum += "C";
}
else
{
implynum += "F";
}
}
System.out.println(implynum);
// 如果implynum等于“TTTT”,表明猜对了,结束循环
if (implynum.equals("TTTT"))
{
System.out
.println("\nCorrect Answer!\nCongratulations!\nYou have succeed!");
break;
}
else
// 如果implynum不等于“TTTT”, 并且猜测次数也达到上限,表明游戏失败
if (j == (times - 1))
{
System.out.println("\nYou have failed!\nGame over!");
System.out.println("\nCorrect Answer is: " + correctAnswer);
}
else
{
System.out.println("Wrong Answer!\nPlease try again!\n");
}
}
}
}