java生成随机数字和字母组合详解编程语言

  
package com.test; 
   
import java.util.Random; 
   
public class GenerateRandomNumber { 
   
    public static void main(String[] args) { 
   
        System.out.println("生成的10为随机数为:" + getCharAndNumr(10)); 
    } 
   
    /** 
     * java生成随机数字和字母组合 
     * @param length[生成随机数的长度] 
     * @return 
     */ 
    public static String getCharAndNumr(int length) { 
        String val = ""; 
        Random random = new Random(); 
        for (int i = 0; i < length; i++) { 
            // 输出字母还是数字 
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
            // 字符串 
            if ("char".equalsIgnoreCase(charOrNum)) { 
                // 取得大写字母还是小写字母 
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;  
                val += (char) (choice + random.nextInt(26)); 
            } else if ("num".equalsIgnoreCase(charOrNum)) { // 数字 
                val += String.valueOf(random.nextInt(10)); 
            } 
        } 
        return val; 
    } 
       
} 
  

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/10667.html

(0)
上一篇 2021年7月19日 10:22
下一篇 2021年7月19日 10:22

相关推荐

发表回复

登录后才能评论