(Analysis of Class Library Use Case) Toss a coin

Use a random number between 0-1 to simulate the coin tossing experiment, and count the number of positive and negative sides after 1000 throws

  • Coin toss
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;
    }
}
  • Main method
    public static void main(String[] args) {
            Coin coin = new Coin();
            coin.throwCoin(1000);
            System.out.println("正面次数为:"+coin.getFront()+"、反面次数为"+coin.getBack());
        }

     

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112725709