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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM