2012-08-23 172 views
0

如何生成隨機字符?Android隨機生成字符

隨機數是這樣的::

public static int random() { 
    Random generator = new Random(); 
    int x = generator.nextInt(10000); 
    return x; 
} 

我需要繪製類似:zCs3v3b1b6只是隨機字符

回答

2
public static char random() { 
    Random generator = new Random(); 
    char x = (char)(generator.nextInt(96) + 32); 
    return x; 
} 

這將產生一個隨機的字符。

public static void main(String[] args) { 
    StringBuilder builder = new StringBuilder(); 
    for (int i = 0; i < 8; i++) 
      builder.append(random()); 
    System.out.println(builder.toString()); 
} 

這將產生8個隨機字符

+0

第一個例子:類型不匹配:不能從int轉換成char – Defuzer

+0

@ user1236390對不起。我用一個類型轉換更新了我的代碼 –

0

字符串見下面鏈接:http://www.asciitable.com/

public static char randomSeriesForThreeCharacter() { 
Random r = new Random(); 
char random_3_Char = (char) (48 + r.nextInt(47)); 
return random_3_Char; 
}