在Java中获取随机布尔值

好的,我在代码中实现了这个SO问题:随机返回True或False

但是,我的行为很奇怪:我需要同时运行十个实例,每个实例每次运行仅返回一次true或false。令人惊讶的是,无论我做什么,每次我得到false

有什么方法可以改善这种方法,以便我至少有大约50%的机会得到true吗?


为了使它更易于理解:我将应用程序构建为JAR文件,然后通过批处理命令运行

 java -jar my-program.jar

pause

程序的内容-使其尽可能简单:

public class myProgram{

public static boolean getRandomBoolean() {

return Math.random() < 0.5;

// I tried another approaches here, still the same result

}

public static void main(String[] args) {

System.out.println(getRandomBoolean());

}

}

如果我打开10个命令行并运行它,false每次都会得到结果…

回答:

我建议使用

Random.nextBoolean()

话虽如此,Math.random() < 0.5就像您使用过的一样。这是我机器上的行为:

$ cat myProgram.java 

public class myProgram{

public static boolean getRandomBoolean() {

return Math.random() < 0.5;

//I tried another approaches here, still the same result

}

public static void main(String[] args) {

System.out.println(getRandomBoolean());

}

}

$ javac myProgram.java

$ java myProgram ; java myProgram; java myProgram; java myProgram

true

false

false

true

不用说, 每次都获得不同的值。但就您而言,我怀疑

A)您未使用自己认为的代码(例如编辑错误的文件)

B)在测试时您没有编写不同的尝试,或者

C)您正在使用一些非标准的无效实现。

以上是 在Java中获取随机布尔值 的全部内容, 来源链接: utcz.com/qa/418062.html

回到顶部