[转]java生成随机数字和字母组合

摘自 http://blog.csdn.net/xiayaxin/article/details/5355851

 1 import java.util.Random;
 2 
 3  
 4 
 5  
 6 
 7 public String getCharAndNumr(int length)   
 8 {   
 9     String val = "";   
10            
11     Random random = new Random();   
12     for(int i = 0; i < length; i++)   
13     {   
14         String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字   
15                
16         if("char".equalsIgnoreCase(charOrNum)) // 字符串   
17         {   
18             int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母   
19             val += (char) (choice + random.nextInt(26));   
20         }   
21         else if("num".equalsIgnoreCase(charOrNum)) // 数字   
22         {   
23             val += String.valueOf(random.nextInt(10));   
24         }   
25     }   
26            
27     return val;   
28 } 

注:

1.方法的参数 length 是生成的随机数的长度。     

2. 只想要大写的字母 可以使 int choice =65; 只想要小写的字母,就 int choice =97;

原文地址:https://www.cnblogs.com/redcoatjk/p/3591501.html