Java生成随机数(n位长度,字母+数字)

 1 package demo;
 2 import java.util.Random;
 3 
 4 /**
 5  * 生成字母+数字的随机数
 6  * @author sy
 7  *
 8  */
 9 public class Demo{
10     
11     public static void main(String[] args){
12         System.out.println(getStringRandom(6));
13     }
14 
15      public static String getStringRandom(int length) {  
16         
17          String val = "";  
18          Random random = new Random();  
19          //参数length,表示生成几位随机数  
20          for(int i = 0; i < length; i++) {  
21             String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
22             //输出字母还是数字  
23             if("char".equalsIgnoreCase(charOrNum)){ 
24                 //输出是大写字母还是小写字母  
25                 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
26                 val += (char)(random.nextInt(26) + temp);  
27             }else if("num".equalsIgnoreCase(charOrNum)) {  
28                 val += String.valueOf(random.nextInt(10));  
29             }  
30         }  
31         return val;  
32     }  
33     
34 }

 

转载于:https://www.cnblogs.com/wanying521/p/5179108.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值