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     }      

 

posted @ 2018-04-02 16:12  现世安稳。  阅读(19027)  评论(0编辑  收藏  举报