返回true或false随机 [英] Return True or False Randomly

查看:4188
本文介绍了返回true或false随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个的Java 方法返回真正随机。我怎样才能做到这一点?

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

推荐答案

java.util.Random中的已经有此功能:

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

}

这篇关于返回true或false随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆