J2ME (Java ME) 環境精簡,無 Math.random(),需使用 java.util.Random 類別生成隨機數。本文系統整理建立物件、生成基本型別隨機數、指定範圍取樣三大主題。
// 方式 1:預設建構子(以系統時間為種子)
Random random = new Random();
// 等價於
Random random = new Random(System.currentTimeMillis());
// 方式 2:指定種子(可重現序列,利於測試)
Random random = new Random(10010010L);
種子相同則產生相同隨機序列,除非需可重現測試,建議使用預設建構子。
// 隨機 int(完整 32 位元範圍,含負數)
int k = random.nextInt();
// 隨機 long(完整 64 位元範圍)
long l = random.nextLong();
// 其他常用方法
boolean b = random.nextBoolean();
float f = random.nextFloat(); // 0.0f ~ 1.0f
double d = random.nextDouble(); // 0.0 ~ 1.0
random.nextBytes(byteArray); // 填充位元組陣列
核心公式:Math.abs(random.nextInt() % n) + min 取得 [min, min+n-1] 範圍整數。
int k = random.nextInt();
int j = Math.abs(k % 10); // 0 ~ 9
int j = Math.abs(random.nextInt() % 15); // 0 ~ 14
int j = Math.abs(random.nextInt() % 10) + 10; // 10 ~ 19
/**
* 取得 [min, max] 區間隨機整數(含邊界)
*/
public static int nextInt(Random random, int min, int max) {
if (min > max) throw new IllegalArgumentException("min > max");
int range = max - min + 1;
return Math.abs(random.nextInt() % range) + min;
}
% 運算結果符號與被除數相同,故需 Math.abs() 確保非負nextInt(int bound)(Java 1.2+ 支援)nextInt()、nextLong(),CLDC 1.1+ 新增 nextInt(int) 等便利方法Random,需 SecureRandom(J2ME 通常不支援)import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
Random r = new Random();
System.out.println("隨機 int: " + r.nextInt());
System.out.println("隨機 long: " + r.nextLong());
System.out.println("0~9: " + Math.abs(r.nextInt() % 10));
System.out.println("10~19: " + (Math.abs(r.nextInt() % 10) + 10));
System.out.println("50~100: " + nextInt(r, 50, 100));
}
static int nextInt(Random random, int min, int max) {
int range = max - min + 1;
return Math.abs(random.nextInt() % range) + min;
}
}