如何生成int特定范圍內的隨機值?
我已經嘗試了以下方法,但是這些方法不起作用:
嘗試1:
randomNum = minimum + (int)(Math.random() * maximum);
錯誤:randomNum可以大于maximum,
嘗試2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
錯誤:randomNum可以小于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實體,如果使用不當,可能會引起混亂和錯誤,
但是,相反,沒有辦法明確設定種子,因此在測驗或保存游戲狀態或類似情況有用的情況下,很難重現結果,在這種情況下,可以使用下面顯示的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.random()更可取,
特別是,當標準庫中有簡單的API完成任務時,就無需重新發明隨機整數生成輪
本文首發于java黑洞網,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/280487.html
標籤:Java
