java随机生成一个6/8/12位密码,数字加字母的密码

代码如下:

数字密码:
方法(1):

    public static void main(String[] args) {
         String code="";
    Random rand=new Random();//生成随机数
    for(int a=0;a<6;a++){
    code+=rand.nextInt(10);//生成6位验证码
      }
      system.out.println("随机数为"+code);
    }

方法(2):
封装的数字密码:

   public static int getRandNum(int min, int max) {
    int randNum = min + (int)(Math.random() * ((max - min) + 1));
    return randNum;
   }
   @Test
   public void rand(){
    System.out.println("随机数为" + getRandNum(1,999999));
   }

方法(3):
数字加字母的密码:

 public class StringRandom {  

    //生成随机数字和字母,  
    public String getStringRandom(int length) {  

        String val = "";  
        Random random = new Random();        
        //length为几位密码 
        for(int i = 0; i < length; i++) {          
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
            //输出字母还是数字  
            if( "char".equalsIgnoreCase(charOrNum) ) {  
                //输出是大写字母还是小写字母  
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
                val += (char)(random.nextInt(26) + temp);  
            } else if( "num".equalsIgnoreCase(charOrNum) ) {  
                val += String.valueOf(random.nextInt(10));  
            }  
        }  
        return val;  
    }  
     //生产的密码包括位数 
    public static void  main(String[] args) {  
        StringRandom test = new StringRandom();  
        System.out.println(test.getStringRandom(6));  
    }  
} 
//随机不重复的6-8位
public static int card(){
       int[] array = {0,1,2,3,4,5,6,7,8,9};
       Random rand = new Random();
       for (int i = 10; i > 1; i--) {
           int index = rand.nextInt(i);
           int tmp = array[index];
           array[index] = array[i - 1];
           array[i - 1] = tmp;
       }
       int result = 0;
       for(int i = 0; i < 6; i++){
           result = result * 10 + array[i];
       }
       return result;
   }
       public static void main(String[] args) {
           System.out.println(card());
       } 
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值