Java 循环习题10道(包含while、do...while、for)

1、改写猜数字游戏

publicstaticvoid main(String[] args) {

       // 记录用户输入的数字

       int guess = -1;

       // 记录用户输入次数

       int count = 0;

       // 生成1-100之间随机数

       int num = (int) (int)(Math.random()*100)+1;

Scanner sc = new Scanner(System.in);

       // 循环猜数字

       do {

           System.out.println("请输入1-100之间的数字");

           guess = sc.nextInt();

           if (guess > num) {

              System.out.println("哥们,太大了");

           } elseif (guess < num) {

              System.out.println("哥们,太小了");

           } else {

              System.out.println("恭喜,中啦");

           }

           count++;

       } while (num != guess);

       System.out.println("你猜测的数字是:" + num + "猜测了" + count + "次");

    }
2、计算器游戏

  ( 系统自动生成2个随机数用于参与运算系统生成0-4之间的随机数,表示加减乘除取模运算 使用switch 进行匹配)

class Couter {

    publicstaticvoid main(String[] args) throws InterruptedException {

         // 生成随机数Math.random()生成0-1值,不包含0和1,

         //乘以10得到0和10之间的数(double类型),不包含0和10

         //强转为int,并加1得到1和10之间的数,包含1和10

        int x = (int)(Math.random()*10)+1;   

        int y = (int)(Math.random()*10)+1;         

        System.out.println(x);

       System.out.println(y);

       // 创建0-4随机数 0 1 2 3 4 各表示加减乘除取模

       int z = (int) (int)(Math.random()*5);

       System.out.println(z);

       switch (z) {

       case 0:

           System.out.println(x + "+" + y + "=?"

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值