java随机布尔值,获取Java中随机布尔

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

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

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

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());

}

}

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

解决方案

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) you're not working with the code you think you are, (like editing the wrong file)

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值