java-隨機生成用戶名(中文版及英文版)


開發中遇到用戶名隨機生成的問題,總結了兩個(中文版和英文版),相關方法在此,方便直接調用。

如下:

復制代碼
 1         //自動生成名字(中文)
 2     public static String getRandomJianHan(int len) {
 3         String ret = "";
 4         for (int i = 0; i < len; i++) {
 5             String str = null;
 6             int hightPos, lowPos; // 定義高低位
 7             Random random = new Random();
 8             hightPos = (176 + Math.abs(random.nextInt(39))); // 獲取高位值
 9             lowPos = (161 + Math.abs(random.nextInt(93))); // 獲取低位值
10             byte[] b = new byte[2];
11             b[0] = (new Integer(hightPos).byteValue());
12             b[1] = (new Integer(lowPos).byteValue());
13             try {
14                 str = new String(b, "GBK"); // 轉成中文
15             } catch (UnsupportedEncodingException ex) {
16                 ex.printStackTrace();
17             }
18             ret += str;
19         }
20         return ret;
21     }
22     
23     //生成隨機用戶名,數字和字母組成,  
24     public String getStringRandom(int length) {  
25           
26         String val = "";  
27         Random random = new Random();  
28           
29         //參數length,表示生成幾位隨機數  
30         for(int i = 0; i < length; i++) {  
31               
32             String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
33             //輸出字母還是數字  
34             if( "char".equalsIgnoreCase(charOrNum) ) {  
35                 //輸出是大寫字母還是小寫字母  
36                 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
37                 val += (char)(random.nextInt(26) + temp);  
38             } else if( "num".equalsIgnoreCase(charOrNum) ) {  
39                 val += String.valueOf(random.nextInt(10));  
40             }  
41         }  
42         return val;  
43     }      
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM