(类库使用案例分析 )扔硬币

用0-1之间的随机数来模拟扔硬币实验,统计扔1000次后出现的正反面次数

  • 抛硬币类
class Coin{ //模拟硬币扔的操作
    private int front;  //保存正面的次数
    private int back;   //保存背面的次数
    private Random random = new Random();

    /**
     * 扔硬币处理
     * @param num 扔硬币的执行次数
     */
    public void throwCoin(int num){
        for(int x  = 0; x < num;x++){
            int temp = random.nextInt(2);   //包括0不包括2
            if(temp == 0){
                this.front++;
            }else{
                this.back++;
            }
        }
    }

    public int getFront(){
        return this.front;
    }
    public int getBack(){
        return this.back;
    }
}
  • 主方法
    public static void main(String[] args) {
            Coin coin = new Coin();
            coin.throwCoin(1000);
            System.out.println("正面次数为:"+coin.getFront()+"、反面次数为"+coin.getBack());
        }

猜你喜欢

转载自blog.csdn.net/weixin_46245201/article/details/112725709