J2ME 無 Math.random(),需使用 java.util.Random 產生偽隨機數。本文涵蓋建立策略、基本方法、指定範圍產生與遊戲實務應用技巧。
// 1. 預設種子(系統時間毫秒數)— 最常用,每次執行序列不同
Random rnd = new Random();
// 等同於
Random rnd = new Random(System.currentTimeMillis());
// 2. 固定種子 — 可重現序列,適合測試/回放/程序化關卡生成
Random rnd = new Random(10010010L); // long 種子
| 方法 | 回傳範圍 | 用途 |
|---|---|---|
nextInt() | 整個 int 範圍 (-2³¹ ~ 2³¹-1) | 通用整數 |
nextLong() | 整個 long 範圍 | 需 64 位隨機位元 |
nextBoolean() | true/false | 布林決策 |
nextFloat() | 0.0f ~ 1.0f | CLDC 1.1+ 支援 float 時可用 |
nextDouble() | 0.0 ~ 1.0 | CLDC 1.1+ 支援 double 時可用 |
nextBytes(byte[] buf) | 填充位元組陣列 | 產生隨機二進位資料 |
核心公式:int result = Math.abs(rnd.nextInt() % range) + min;
range = max - min + 1Math.abs() 處理負數餘數// 0 ~ 9
int n = Math.abs(rnd.nextInt() % 10);
// 1 ~ 10
int n = Math.abs(rnd.nextInt() % 10) + 1;
// 10 ~ 20
int n = Math.abs(rnd.nextInt() % 11) + 10; // range=11
// -5 ~ 5
int n = Math.abs(rnd.nextInt() % 11) - 5;
nextInt() % n 當 n 非 2 的冪次時分布略不均勻。嚴格均勻需求可用拒絕採樣法(J2ME 通常可忽略)for (int i = deck.length - 1; i > 0; i--) {
int j = Math.abs(rnd.nextInt() % (i + 1));
swap(deck, i, j);
}
Random 輕量,可頻繁呼叫。避免在 paint() 迴圈中建立新實例