2011-11-14 40 views

回答

2

那麼,你首先寫一個函數,它會給你一個隨機的字符滿足你的要求,然後根據所需的長度將它包裝在for循環中。

以下程序給出這樣一來,使用一組字符常量池和一個隨機數發生器的一種方法:

import java.util.Random; 

public class testprog { 
    private static final char[] pool = { 
     'a','b','c','d','e','f','g', 
     'h','i','j','k','l','m','n', 
     'o','p','q','r','s','t','u', 
     'v','w','x','y','z'}; 

    private Random rnd; 

    public testprog() { rnd = new Random(); } 

    public char getChar() { return pool[rnd.nextInt(pool.length)]; } 

    public String getStr(int sz) { 
     StringBuilder sb = new StringBuilder(); 
     for (int i = 0; i < sz; i++) 
      sb.append(getChar()); 
     return new String(sb); 
    } 

    public static void main(String[] args) { 
     testprog tp = new testprog(); 
     for (int i = 0; i < 10; i++) 
      System.out.println (tp.getStr(i+5)); 
    } 
} 

在一個特定的運行,這給了我:

hgtbf 
xismun 
cfdnazi 
cmpczbal 
vhhxwjzbx 
gfjxgihqhh 
yjgiwnftcnv 
ognwcvjucdnm 
hxiyqjyfkqenq 
jwmncfsrynuwed 

現在,您可以調整字符池,如果您希望使用不同的字符集,您甚至可以通過更改在陣列中出現的頻率來調整對特定字符的傾斜(更多e字符比z,對於e xample)。

但是,這應該是你嘗試做的一個好的開始。

4

以下是生成兩種類型字符串的示例。

import java.security.SecureRandom; 
import java.math.BigInteger; 

public final class SessionIdentifierGenerator 
{ 

    private SecureRandom random = new SecureRandom(); 

    public String nextSessionId() 
    { 
    return new BigInteger(130, random).toString(32); 
    } 

} 

輸出:ponhbh78cqjahls5flbdf4dlu4

參考here

String uuid = UUID.randomUUID().toString(); 
System.out.println("uuid = " + uuid); 

輸出:281211f4-c1d7-457a-9758-555041a5ff97

參考here

+1

這裏是我的答案...您的文章是非常有用......非常感謝 公共類RandomeString { \t \t公共焦炭randomNumber(){ \t \t INT randomNum = 97 + (新隨機())。nextInt(122-97); \t \t char randomChar =(char)randomNum; \t \t return randomChar; } \t \t公共字符串隨機量(INT N){ \t \t \t StringBuilder的SB =新的StringBuilder(); \t \t \t \t \t \t對(INT I = 0; I Rojin