Get random boolean in Java

后端 未结 10 1573
情深已故
情深已故 2020-12-01 11:28

Okay, I implemented this SO question to my code: Return True or False Randomly

But, I have strange behavior: I need to run ten instances simultaneously, where every

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 12:06

    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;
    

提交回复
热议问题