Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 隨機數實作:字母與數字的組合產生

編輯:關於 Android 程式設計

這篇記錄一個很基礎但常需要用到的需求:產生由字母與數字混搭的隨機字串,例如驗證碼。

關鍵觀念只有一個:ASCII 是連續的。大寫 A 是 65,小寫 a 是 97,因此「隨機取一個字母」可以拆成兩步——先決定大小寫,再用 random.nextInt(26) 取 0 到 25 的位移量加到基數上,最後轉成 char。數字則是 random.nextInt(10)。

以下是我當時寫的版本,把註解掉的嘗試過程也保留下來,方便對照思路:

public void getCharAndNumr() {
    String a = "", b = "", c = "", d = "";
    Random random = new Random();

    // 決定 a、b 兩個位置是大寫還是小寫
    int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;   // 65 = 'A',97 = 'a'
    a += (char) (choice + random.nextInt(26));
    b += (char) (choice + random.nextInt(26));

    choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
    a += (char) (choice + random.nextInt(26));

    // c、d 兩個位置放數字 1~9
    c = String.valueOf((int) (Math.random() * 9 + 1));
    d = String.valueOf((int) (Math.random() * 9 + 1));

    TextView tw1 = (TextView) findViewById(R.id.textView3);
    tw1.setText(a + c + b + d);
}

仔細看會發現這段程式有個 bug:位置 a 被寫入了兩次,第一次的結果被第二次覆蓋掉了。這正是即興拼湊程式碼時最容易出現的問題——寫到一半改了主意,舊的那行忘了刪。

整理後的版本

如果重寫一次,我會把它收斂成一個語意清楚的小函式,讓「取一個隨機字母」這件事只有一個出口:

/** 產生一個隨機英文字母 */
private static char randomLetter(Random random) {
    int base = random.nextBoolean() ? 'A' : 'a';
    return (char) (base + random.nextInt(26));
}

/** 產生指定長度的字母數字混合字串 */
private static String randomCode(int length) {
    Random random = new Random();
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
        // 一半機率放字母,一半放數字
        if (random.nextBoolean()) {
            sb.append(randomLetter(random));
        } else {
            sb.append(random.nextInt(10));
        }
    }
    return sb.toString();
}

幾個實務提醒

用 nextBoolean() 取代 nextInt(2) % 2 == 0。後者雖然能動,但語意不夠直接,而且多了一次取模運算。

用 StringBuilder 而非字串串接。在迴圈裡反覆做 s += x 每次都會產生新的字串物件,長度一大就是不必要的記憶體浪費。

Math.random() 與 Random 擇一即可。兩者底層是同一套機制,混用只會讓程式看起來沒有頭緒。

若用於安全用途請改用 SecureRandom。驗證碼、權杖、臨時密鑰這類情境,Random 的線性同餘演算法是可預測的,必須換成 java.security.SecureRandom。另外,若驗證碼容易混淆,建議排除 0 與 O、1 與 l、2 與 Z 這類形近字元。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved