簡體   English   中英

隨機返回真或假

[英]Return True or False Randomly

我需要創建一個Java方法來隨機返回truefalse 我怎樣才能做到這一點?

java.util.Random類已經有這個功能:

public boolean getRandomBoolean() {
    Random random = new Random();
    return random.nextBoolean();
}

但是,每次需要隨機布爾值時總是創建一個新的Random實例並不高效。 相反,在您的類中創建一個需要隨機布爾值的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)隨機返回真或假

這應該這樣做:

public boolean randomBoolean(){
    return Math.random() < 0.5;
}

您可以使用以下代碼

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;

您可以使用以下內容來獲得公正的結果:

Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

注意: random.nextInt(2) 表示數字 2 是界限。 計數從 0 開始。所以我們有 2 個可能的數字(0 和 1),因此概率是 50%!

如果你想讓你的結果更有可能是真(或假),你可以調整上面的如下!

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 的Random類使用 CPU 的內部時鍾(據我所知)。 類似地,可以使用 RAM 信息作為隨機性的來源。 只需打開 Windows 任務管理器的性能選項卡,然后查看物理內存 - 可用:它不斷變化; 大多數情況下,該值大約每秒更新一次,只有在極少數情況下,該值會在幾秒鍾內保持不變。 其他更頻繁更改的值是 System Handles 和 Threads ,但我沒有找到cmd命令來獲取它們的值。 所以在本例中,我將使用可用物理內存作為隨機源。

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

如您所見,核心部分是使用Runtime.getRuntime().exec()運行 cmd systeminfo命令。

為簡潔起見,我省略了 try-catch 語句。 我多次運行這個程序,沒有發生錯誤——在 cmd 命令的輸出中總是有一個“可用物理內存”行。

可能的缺點:

  1. 執行這個程序有一些延遲。 請注意,在main()函數中,在while(true)循環內,沒有Thread.sleep()並且輸出僅大約每秒打印一次到控制台。
  2. 對於新打開的操作系統會話,可用內存可能是恆定的 - 請驗證。 我只運行了幾個程序,並且值每秒都在變化。 我想如果你在服務器環境中運行這個程序,每次調用獲得不同的值應該不是問題。

ThreadLocalRandom.current().nextBoolean()

為避免重新創建Random對象,請使用ThreadLocalRandom 每個線程只有一個這樣的對象。

boolean rando = ThreadLocalRandom.current().nextBoolean() ;

該代碼非常簡短且易於記住,您無需按照問題中的要求創建專用方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM