猜密码小游戏
1.利用随机数组生成1~1000以内的随机数()
Random random = new Random();
int i = random.nextInt(1000);
2.若生成的随机数小于100,转换后的字符串密码就不到3位,补充代码使得随机数小于100时,生成的字符串密码也是3位,(高位补0)
// 字符串高位补零
public String addZeroFornum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer in = new StringBuffer();
in.append("0").append("0");// 左补零
// in.append(str).append("0");//右补零
str = in.toString();
strLen = str.length();
}
}
return str;
}
3.利用生成的随机数转换为密码
// 系统随机生成密码
public String passwordCreat(int random) {
String password = Integer.toString(random);
if (random < 100) {
password = this.addZeroFornum(password, 3);
}
return password;
}
4.用户输入密码:String userInput
把用户输入的密码与系统生成的随机密码比较,告诉用户猜对了几位密码的数字,增大用户猜对密码的概率
// 字符串比较函数
public void stringGet(String userInput, String password1) {
char a, b;
for (int i = 0; i < userInput.length(); i++) {
a = userInput.charAt(i);
b = password1.charAt(i);
if (a == b) {
System.out.println("恭喜你,您猜对了密码的第" + (i + 1) + "位");
} else {
System.out.println("很遗憾,您没有猜对密码的第" + (i + 1) + "位");
}
}
System.out.print("请按任意键继续");
Scanner in = new Scanner(System.in);
in.nextLine();
// in.close();
}
5.记录用户猜对的次数: times
用户可猜的最大次数: MAX_GUESS_TIMES
//主干测试代码
while (times < MAX_GUESS_TIMES) {
System.out.print("请输入您要猜的数字:");
Scanner in = new Scanner(System.in);
userInput = in.nextLine();
times++;
if (userInput.length() > 3) {
System.out.println("您输入的密码位数不正确,请重新输入");
} else {
if (userInput.equals(password1)) {
System.out.print("恭喜您,您用" + times + "次猜对了密码");
System.exit(0);
} else {
HomeWorkRandom abs = new HomeWorkRandom();
abs.stringGet(userInput, password1);
}
}
// in.close();
}
6:测试结果案例:
请输入您要猜的数字:456
很遗憾,您没有猜对密码的第1位
很遗憾,您没有猜对密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:123
恭喜你,您猜对了密码的第1位
很遗憾,您没有猜对密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:134
恭喜你,您猜对了密码的第1位
很遗憾,您没有猜对密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:156
恭喜你,您猜对了密码的第1位
很遗憾,您没有猜对密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:178
恭喜你,您猜对了密码的第1位
很遗憾,您没有猜对密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:189
恭喜你,您猜对了密码的第1位
很遗憾,您没有猜对密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:147
恭喜你,您猜对了密码的第1位
恭喜你,您猜对了密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:140
恭喜你,您猜对了密码的第1位
恭喜你,您猜对了密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:141
恭喜你,您猜对了密码的第1位
恭喜你,您猜对了密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:142
恭喜你,您猜对了密码的第1位
恭喜你,您猜对了密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:143
恭喜你,您猜对了密码的第1位
恭喜你,您猜对了密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:144
恭喜你,您猜对了密码的第1位
恭喜你,您猜对了密码的第2位
很遗憾,您没有猜对密码的第3位
请按任意键继续
请输入您要猜的数字:145
恭喜您,您用13次猜对了密码