package cn.tedu;
import java.util.Scanner;
public class GuessNum {
public static void main(String[] args) {
// 定义十次机会
int choose = 10;
int score = 0;
System.out.println("猜数字游戏");
System.out.println("数字在1-20之间");
int random = 1 + (int) (20 * Math.random());
while (random != 0) {
System.out.println("输入你拆的数字: ");
int guess = new Scanner(System.in).nextInt();
// 如果猜的数字和随机数相同,则打印成功信息和积分,并初始化机会和随机数
if (guess == random) {
score++;
System.out.println("展示您的分数:" + score);
System.out.println("猜对了!");
choose = 10;
random = 1 + (int) (20 * Math.random());
} else {
// 如果猜错了,则机会减一,并警告及显示提示信息
choose--;
if (choose > 0) {
System.out.println("你当前还有" + choose + "次机会,请注意!");
}
if (guess < random) {
System.out.println("你猜的数字太小了!");
} else {
System.out.println("你猜的数字太大了!");
}
}
// 如果机会小于0 则游戏失败,终结程序
if (choose <= 0) {
System.out.println("机会用完了!Game Over!");
System.out.println("展示正确的答案:" + random);
System.out.println("展示您的分数:" + score);
return;
}
}
}
}