目录
游戏规则:
程序产生一个[1, 100]之间的随机整数,用户输入整数进行猜测,如果猜对了,就结束游戏;如果猜错了,程序会提示你是猜高了还是猜低了,然后让你继续输入整数进行猜测。
(一)编程实现
- 在net.yangxinying.p02.t06包里创建Task06类
-
public class Task06 {
public static void main(String[] args) {
//声明部分
int target, x;
Scanner sc = new Scanner(System.in);
//产生猜测目标
Random random = new Random();
target = random.nextInt( 100);
//用户输入猜测的数
System.out.print("输入一个[1,100]的整数:");
x = sc.nextInt();
//判断用户是否猜测正确
while (x != target) {
if (x > target) {
System.out.println("朋友,你猜高了,继续猜吧~");
} else {
System.out.println("朋友,你猜低了,继续猜吧~");
}
// 用户输入猜测的数
System.out.print("输入一个[1,100]的整数:");
x = sc.nextInt();
}
System.out.println("恭喜,你猜对了,游戏结束!");
}
}
- 运行程序,查看结果
- 在net.yangxinying.p02.t06包里创建Task06_类
public class Task06_ {
public static void main(String[] args) {
//声明部分
int target, x;
Scanner sc = new Scanner(System.in);
//产生猜测目标
Random random = new Random();
target = random.nextInt( 100);
while (true) {
//用户输入猜测的数
System.out.print("输入一个[1,100]的整数:");
x = sc.nextInt();
//判断用户是否猜测正确
if (x > target) {
System.out.println("朋友,你猜高了,继续猜吧~");
} else if (x < target) {
System.out.println("朋友,你猜低了,继续猜吧~");
}else {
break; //猜中了,跳出循环
}
}
System.out.println("恭喜,你猜对了,游戏结束!");
}
}
- 运行程序,查看结果
(二)讲解知识点
1、前测试条件循环 - while循环
(1)语法格式
初始条件
while (循环条件) {
语句块
break|continue;
更新条件
}
(2)执行情况
- 首先判断循环条件是真还是假,如果是真的,执行循环体,然后再次判断循环条件。如果是真的,继续循环,直到循环条件变成假的。有一种特殊情况:如果第一次判断循环条件就不成立,那么一次循环也不执行。
2、后测试条件循环 - do…while循环
(1)语法格式
初始条件
do {
语句块
break|continue;
更新条件
} while (循环条件);
(2)执行情况
- 首先执行一次循环,然后判断循环条件,如果为真,继续循环,直到条件为假时结束循环。后测试当型循环,属于先上车后买票,无论如何都会执行一次循环。
3、随机类 - Random
- 查看Random的方法
- 产生指定范围的随机整数[a, b]
Random random = new Random();
int x = a + random.nextInt(b - a);