package task;
import java.util.Random;
import java.util.Scanner;
//编写猜数游戏
public class Demo1005 {
public static void main(String[] args) {
//产生一个0到100的随机数
Random rd = new Random();
int number = rd.nextInt(0, 100) + 1;
//从键盘输入
Scanner sc = new Scanner(System.in);
System.out.println(number);
//统计猜的次数
int step = 0;
while (true) {
//每猜一次次数加一
++step;
System.out.println("请输入一个 1~100 之间的整数:");
int printNumber = sc.nextInt();
//输出相应提示
if (printNumber > number) {
System.out.println("第" + step + "次猜" + "\033[31m抱歉猜大了\033[0m");
} else if (printNumber < number) {
System.out.println("第" + step + "次猜" + "\033[31m抱歉猜小了\033[0m");
} else {
System.out.println("第" + step + "次猜" + "\033[32m恭喜你猜对了\033[0m");
//猜对后跳出循环
break;
}
}
}
}
Java之while简单猜数字小游戏详细讲解
最新推荐文章于 2024-03-19 00:25:29 发布