首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

J2ME 隨機數生成完整攻略:從基礎到指定範圍實作

     編輯:Java 相關知識

J2ME (Java ME) 環境精簡,無 Math.random(),需使用 java.util.Random 類別生成隨機數。本文系統整理建立物件、生成基本型別隨機數、指定範圍取樣三大主題。

一、建立 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] 範圍整數。

範例 1:0 ~ 9(10 個數)

int k = random.nextInt();
int j = Math.abs(k % 10);  // 0 ~ 9

範例 2:0 ~ 14(15 個數)

int j = Math.abs(random.nextInt() % 15);  // 0 ~ 14

範例 3:10 ~ 19(10 個數,最小值 10)

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;
}

四、注意事項與進階補充

  • 負數餘數問題:Java % 運算結果符號與被除數相同,故需 Math.abs() 確保非負
  • 分布均勻性:取模法在範圍非 2 的冪次時略有偏差,極嚴格場景建議用 nextInt(int bound)(Java 1.2+ 支援)
  • J2ME 版本差異:CLDC 1.0 僅有 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;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved