問題

如何在特定範圍內生成隨機int值?

我嘗試了以下內容,但這些不起作用:

嘗試1:

 randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
 

嘗試2:

 Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
 

  最佳答案

在Java 1.7或更晚時,標準方法如下:

 import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
 

相關的JavaDoc .這種方法的優點是不需要顯式初始化 java.util.Random 例項,如果不當使用,它可能是混淆和錯誤的來源.

但相反,沒有辦法顯式設定種子,以便在有用的情況下重現結果,例如測試或儲存遊戲狀態或類似.在這些情況下,可以使用下面顯示的pre-Java 1.7技術.

在Java 1.7之前,標準方法如下:

 import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    // 
    // In particular, do NOT do 'Random rand = new Random()' here or you
    // will get not very good / not very random results.
    Random rand;

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}
 

相關的JavaDoc .在實踐中, java.util.Random 類通常比 java.lang.Math.radom() 更好.

特別是,當標準庫中有一個簡單的 API 來完成任務時,沒有必要重新建立隨機整數生成輪。

  相同標籤的其他問題

javarandomintegerjava-8
上一個問題: