Return True or False Randomly

2019-01-31 02:45发布

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

5条回答
Summer. ? 凉城
2楼-- · 2019-01-31 03:08

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

}
查看更多
乱世女痞
3楼-- · 2019-01-31 03:13

(Math.random() < 0.5) returns true or false randomly

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-31 03:16

You will get it by this:

return Math.random() < 0.5;
查看更多
贼婆χ
5楼-- · 2019-01-31 03:17

This should do:

public boolean randomBoolean(){
    return Math.random() < 0.5;
}
查看更多
小情绪 Triste *
6楼-- · 2019-01-31 03:17

You can do as following code,

public class RandomBoolean {
    Random random = new Random();
    public boolean getBoolean() {
        return random.nextBoolean();
    }
    public static void main(String[] args) {
        RandomBoolean randomBoolean = new RandomBoolean();
        for (int i = 0; i < 10; i++) {
            System.out.println(randomBoolean.getBoolean());
        }
    }
}

Hope this would help you, Thanks.

查看更多
登录 后发表回答