获取Java中随机布尔 [英] Get random boolean in java

查看:290
本文介绍了获取Java中随机布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我实现这太问题到我的code:返回TRUE或FALSE随机

Okay, I implemented this SO question to my code: Return True or False Randomly

不过,我有奇怪的行为:我需要同时运行个实例,其中每个实例每次运行返回true或false一次。令人奇怪的是,无论我做什么,我每次得到的只是

But, I have strange behavior: I need to run ten instances simultaneously, where every instance returns true or false just once per run. And surprisingly, no matter what I do, every time i get just false

有什么改善的方法,所以我可以至少有大约50%的机会获得真正

Is there something to improve the method so I can have at least roughly 50% chance to get true?

要使其更容易理解:我有我的应用程序建造到JAR文件,然后通过批处理命令运行

To make it more understandable: I have my application builded to JAR file which is then run via batch command

 java -jar my-program.jar
 pause

该方案的

内容 - 以使其尽可能简单:

Content of the program - to make it as simple as possible:

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命令行并运行它,我得到作为结果每次...

If I open 10 command lines and run it, I get false as result every time...

推荐答案

我建议使用的 Random.nextBoolean()

I recommend using Random.nextBoolean()

话虽这么说,的Math.random()&LT; 0.5 因为你已经使用过的作品。这里是我的机器上的行为:

That being said, Math.random() < 0.5 as you have used works too. Here's the behavior on my machine:

$ 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

不用说了,还有的无保证,每次得到不同的值。你的情况然而,我怀疑

Needless to say, there are no guarantees for getting different values each time. In your case however, I suspect that

A)你不与code你以为你是工作,(如编辑错误的文件)

A) you're not working with the code you think you are, (like editing the wrong file)

B)您没有带编译了不同的尝试进行测试时,或

B) you havn't compiled your different attempts when testing, or

C)你有一些不规范的实施断工作。

C) you're working with some non-standard broken implementation.

这篇关于获取Java中随机布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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