Get random boolean in Java

后端 未结 10 1563
情深已故
情深已故 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条回答
  •  Happy的楠姐
    2020-12-01 12:27

    You can also make two random integers and verify if they are the same, this gives you more control over the probabilities.

    Random rand = new Random();
    

    Declare a range to manage random probability. In this example, there is a 50% chance of being true.

    int range = 2;
    

    Generate 2 random integers.

    int a = rand.nextInt(range);
    int b = rand.nextInt(range);
    

    Then simply compare return the value.

    return a == b; 
    

    I also have a class you can use. RandomRange.java

提交回复
热议问题