Return True or False Randomly

前端 未结 7 1261
傲寒
傲寒 2020-12-23 10:59

I need to create a Java method to return true or false randomly. How can I do this?

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 11:34

    You can use the following for an unbiased result:

    Random random = new Random();
    //For 50% chance of true
    boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
    

    Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!

    If you want to give more probability to your result to be true (or false) you can adjust the above as following!

    Random random = new Random();
    
    //For 50% chance of true
    boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
    
    //For 25% chance of true
    boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;
    
    //For 40% chance of true
    boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;
    

提交回复
热议问题