[英]Return True or False Randomly
I need to create a Java method to return true
or false
randomly.我需要创建一个Java方法来随机返回
true
或false
。 How can I do this?我怎样才能做到这一点?
The class java.util.Random
already has this functionality: 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.但是,每次需要随机布尔值时总是创建一个新的
Random
实例并不高效。 Instead, create a attribute of type Random
in your class that needs the random boolean, then use that instance for each new random booleans:相反,在您的类中创建一个需要随机布尔值的
Random
类型的属性,然后将该实例用于每个新的随机布尔值:
public class YourClass {
/* Oher stuff here */
private Random random;
public YourClass() {
// ...
random = new Random();
}
public boolean getRandomBoolean() {
return random.nextBoolean();
}
/* More stuff here */
}
(Math.random() < 0.5)
随机返回真或假
This should do:这应该这样做:
public boolean randomBoolean(){
return Math.random() < 0.5;
}
You can use the 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());
}
}
}
你会得到它:
return Math.random() < 0.5;
You can use the following for an unbiased result:您可以使用以下内容来获得公正的结果:
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
Note: random.nextInt(2) means that the number 2 is the bound.注意: random.nextInt(2) 表示数字 2 是界限。 the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!
计数从 0 开始。所以我们有 2 个可能的数字(0 和 1),因此概率是 50%!
If you want to give more probability to your result to be true (or false) you can adjust the above as following!如果你想让你的结果更有可能是真(或假),你可以调整上面的如下!
Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;
//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;
//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;
Java's Random
class makes use of the CPU's internal clock (as far as I know). Java 的
Random
类使用 CPU 的内部时钟(据我所知)。 Similarly, one can use RAM information as a source of randomness.类似地,可以使用 RAM 信息作为随机性的来源。 Just open Windows Task Manager, the Performance tab, and take a look at Physical Memory - Available: it changes continuously;
只需打开 Windows 任务管理器的性能选项卡,然后查看物理内存 - 可用:它不断变化; most of the time, the value updates about every second, only in rare cases the value remains constant for a few seconds.
大多数情况下,该值大约每秒更新一次,只有在极少数情况下,该值会在几秒钟内保持不变。 Other values that change even more often are System Handles and Threads , but I did not find the
cmd
command to get their value.其他更频繁更改的值是 System Handles 和 Threads ,但我没有找到
cmd
命令来获取它们的值。 So in this example I will use the Available Physical Memory as a source of randomness.所以在本例中,我将使用可用物理内存作为随机源。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public String getAvailablePhysicalMemoryAsString() throws IOException
{
Process p = Runtime.getRuntime().exec("cmd /C systeminfo | find \"Available Physical Memory\"");
BufferedReader in =
new BufferedReader(new InputStreamReader(p.getInputStream()));
return in.readLine();
}
public int getAvailablePhysicalMemoryValue() throws IOException
{
String text = getAvailablePhysicalMemoryAsString();
int begin = text.indexOf(":")+1;
int end = text.lastIndexOf("MB");
String value = text.substring(begin, end).trim();
int intValue = Integer.parseInt(value);
System.out.println("available physical memory in MB = "+intValue);
return intValue;
}
public boolean getRandomBoolean() throws IOException
{
int randomInt = getAvailablePhysicalMemoryValue();
return (randomInt%2==1);
}
public static void main(String args[]) throws IOException
{
Main m = new Main();
while(true)
{
System.out.println(m.getRandomBoolean());
}
}
}
As you can see, the core part is running the cmd systeminfo
command, with Runtime.getRuntime().exec()
.如您所见,核心部分是使用
Runtime.getRuntime().exec()
运行 cmd systeminfo
命令。
For the sake of brevity, I have omitted try-catch statements.为简洁起见,我省略了 try-catch 语句。 I ran this program several times and no error occured - there is always an 'Available Physical Memory' line in the output of the cmd command.
我多次运行这个程序,没有发生错误——在 cmd 命令的输出中总是有一个“可用物理内存”行。
Possible drawbacks:可能的缺点:
main()
function , inside the while(true)
loop, there is no Thread.sleep()
and still, output is printed to console only about once a second or so.main()
函数中,在while(true)
循环内,没有Thread.sleep()
并且输出仅大约每秒打印一次到控制台。ThreadLocalRandom.current().nextBoolean()
To avoid recreating Random
objects, use ThreadLocalRandom
.为避免重新创建
Random
对象,请使用ThreadLocalRandom
。 Every thread has just one such object.每个线程只有一个这样的对象。
boolean rando = ThreadLocalRandom.current().nextBoolean() ;
That code is so short and easy to remember that you need not bother to create a dedicated method as asked in the Question.该代码非常简短且易于记住,您无需按照问题中的要求创建专用方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.