用do...while...编写猜数字游戏
1 package Cforth; 2 3 import java.util.*; 4 5 public class C4_8 { 6 public static void main(String[] args) { 7 Scanner in = new Scanner(System.in); 8 System.out.println(""); 9 Random myrandom = new Random(); 10 int a = myrandom.nextInt(101);// 生成0-100之间的数 11 int number = 0; 12 do { 13 System.out.println("请猜一下电脑随机生成的数:"); 14 number = in.nextInt(); 15 if (number < a) { 16 System.out.println("小了"); 17 18 } else if (number > a) { 19 System.out.println("大了"); 20 } 21 } while (number != a); 22 System.out.println("恭喜你猜对了"); 23 24 } 25 }
注意:
1.在do ...while..中使用if ..else if..
2.在do..while..中同样使用调用Scanner函数
测试结果:
测试成功!