使用Java中Random类完成猜拳游戏

我们先来学习一下如何利用java.util.Random类来产生随机数:

我在代码中做了详细解释

// 收获:学会了如何产生随机数
import java.util.Random;
public class Main {
    public static void main(String[] args) {
        Random r = new Random(); // 以当前时间戳为随机数种子

        int randomNum1 = r.nextInt(); // 不指定范围,则随机返回
        System.out.println(randomNum1); // 如输出:411083125 1667252093 -1073984464

        float randomNum2 = r.nextFloat(); // 不指定范围,则随机返回(0,1)的浮点数
        System.out.println(randomNum2); // 如输出:0.4867543 0.6756566 0.75462216

        double randomNum3 = r.nextDouble(); // 不指定范围,则随机返回(0,1)的浮点数
        System.out.println(randomNum3); // 如输出:0.3578593626934057 0.847467617684877 0.3678703267673402 0.021077179858513984 0.7042241066311454

        // 左闭右开区间
        int randomNum4 = r.nextInt(1,2);
        System.out.println(randomNum4);

        float randomNum5 = r.nextFloat((float) 3.4,(float)5.6); // 实数默认为double类型
        System.out.println(randomNum5);

        double randomNum6 = r.nextDouble(2.1,3.2);
        System.out.println(randomNum6);
        /*一个输出案例
            1
            3.9687438
            2.1610993247736427
         */
    }
}

现在就让我们来实现一下猜拳游戏吧

import java.util.Random;
public class Main {
    public static void main(String[] args) {
        Random r = new Random(); // 以当前时间戳为随机数种子
        int[] book = new int[3]; // 记录当前数字能打赢哪个数字
        book[0] = 1;
        book[1] = 2;
        // book[2] = 0; 默认为0了

        GuessGame computer = new GuessGame();
        int cnt1 = 0, cnt2 = 0; // 记录win和lose的次数
        for(int i = 0; i < 3; i++) { // 猜三次
            int num = r.nextInt(3); // 开区间
            int comnum = computer.getrandom();

            // 0石头 1剪刀 2布
            if(num == comnum) continue;
            if(book[num] == comnum) cnt1 ++;
            else cnt2 ++;
        }

        // 输出结果
        System.out.println("Tom赢的次数为:" + cnt1);
        System.out.println("Tom输的次数为:" + cnt2);
    }
}

class GuessGame {
    public int getrandom() {
        Random r = new Random();
        return r.nextInt(3);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值