Math.random() 能夠產生一個 大於等於 0 且 小於 1 的雙精度僞隨機數,假設須要產生 」0<= 隨機數 <=10」 的隨機數,能夠這樣作:html
int num =(int)(Math.random() * 11);
那如何產生 「5<= 隨機數 <= 10」 的隨機數呢?java
int num = 5 + (int)(Math.random() * 6);
生成 「min <= 隨機數 <= max 」 的隨機數apache
int num = min + (int)(Math.random() * (max-min+1));
Random 是 java 提供的一個僞隨機數生成器。api
生成 「min <= 隨機數 <= max 」 的隨機數:oracle
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: Usually this should be a field rather than a method // variable so that it is not re-seeded every call. Random rand = new Random(); // 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; }
在實際使用中,沒有必要區從新寫一次這些隨機數的生成規則,能夠藉助一些標準庫完成。如 commons-lang.dom
org.apache.commons.lang3.RandomUtils 提供了以下產生指定範圍的隨機數方法:this
// 產生 start <= 隨機數 < end 的隨機整數 public static int nextInt(final int startInclusive, final int endExclusive); // 產生 start <= 隨機數 < end 的隨機長整數 public static long nextLong(final long startInclusive, final long endExclusive); // 產生 start <= 隨機數 < end 的隨機雙精度數 public static double nextDouble(final double startInclusive, final double endInclusive); // 產生 start <= 隨機數 < end 的隨機浮點數 public static float nextFloat(final float startInclusive, final float endInclusive);
org.apache.commons.lang3.RandomStringUtils 提供了生成隨機字符串的方法,簡單介紹一下:spa
// 生成指定個數的隨機數字串 public static String randomNumeric(final int count); // 生成指定個數的隨機字母串 public static String randomAlphabetic(final int count); // 生成指定個數的隨機字母數字串 public static String randomAlphanumeric(final int count);