J2ME 無 Math.random(),唯一標準來源為 java.util.Random。
// 1. 預設種子 = System.currentTimeMillis()
Random r = new Random();
// 2. 固定種子 (可重現序列,利於測試)
Random r = new Random(10010010L);
// 等價於
Random r = new Random(System.currentTimeMillis());
int i = r.nextInt(); // 32 位有號整數 (含負數)
long l = r.nextLong(); // 64 位長整數
boolean b = r.nextBoolean(); // CLDC 1.1+ 支援
float f = r.nextFloat(); // CLDC 1.1+ 需浮點支援
double d = r.nextDouble(); // 同上
byte[] buf = new byte[16];
r.nextBytes(buf); // 填充位元組陣列
// 取 [0, n) 區間
int value = Math.abs(r.nextInt() % n);
// 取 [min, max] 區間
int value = Math.abs(r.nextInt() % (max - min + 1)) + min;
// 範例:0-9
int d = Math.abs(r.nextInt() % 10);
// 範例:10-20
int d = Math.abs(r.nextInt() % 11) + 10;
nextInt() 回傳負數,必須搭配 Math.abs() 後再取模,否則結果可能為負。Integer.MAX_VALUE 非 n 的倍數時略有偏差,遊戲級應用可接受;嚴格均勻需用拒絕採樣 (效能較差)。nextInt()、nextLong()、nextBytes();nextBoolean/Float/Double 需 CLDC 1.1。// Fisher-Yates 洗牌 (陣列原地打亂)
for (int i = arr.length - 1; i > 0; i--) {
int j = Math.abs(r.nextInt() % (i + 1));
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}