Return True or False Randomly

前端 未结 7 1196
傲寒
傲寒 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:50

    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 */
    
    }
    

提交回复
热议问题