语法:
do{循环体}
while (条件表达式);
说明:do-while语句和while有些不一样,do-while是会先执行一遍循环体里面的,然后再判断条件表达式,是否为真,为真,会再去执行循环体里面的,直到条件表达式为假时,跳出循环体,执行后面的语句;
1 import java.util.Random;
2 import java.util.Scanner;
3 public class Test5 {
4 public static void main(String[] args) {
5 //猜数字游戏
6 //创建1-100随机数
7 Random random = new Random();
8 System.out.println("输随机数字:");
9 int i = random.nextInt(100);
10 Scanner input = new Scanner(System.in);//键盘获取
11 int guess;//定义猜的数字
12 guess = input.nextInt();
13 do {
14 if (guess > i) {
15 System.out.println("才猜打了,继续猜");
16 guess = input.nextInt();//每次要去获取才进行下一次
17 } else if (guess < i) {
18 System.out.println("猜小了,继续猜");
19 guess = input.nextInt();
20 }
21
22 } while (guess != i);
23 System.out.println("猜对了");
24 }
25 }