I need to create a Java method to return true
or false
randomly. How can I do this?
In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.
The random. random() function generated a random floating number between 0 and 1. The generated number is compared with 0 by using the if() function. If the generated number is greater than 0, the used method will return True as output, else it will return False.
The nextBoolean() method of the Random class is an instance method that generates pseudorandom, uniformly distributed Boolean values. True and false values are generated with approximately equal probability.
Until now I used the following code to generate a random bool : bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);
The class java.util.Random
already has this functionality:
public boolean getRandomBoolean() { Random random = new Random(); return random.nextBoolean(); }
However, it's not efficient to always create a new Random
instance each time you need a random boolean. Instead, create a attribute of type Random
in your class that needs the random boolean, then use that instance for each new random booleans:
public class YourClass { /* Oher stuff here */ private Random random; public YourClass() { // ... random = new Random(); } public boolean getRandomBoolean() { return random.nextBoolean(); } /* More stuff here */ }
(Math.random() < 0.5)
returns true or false randomly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With