1. 程式人生 > >生成6位隨機數(帶英文)

生成6位隨機數(帶英文)

package test;

import java.util.*;

public class  randomNumUtils{
    /*
    程式實現的是打印出6位驗證碼有字元有數字交替出現
    */
     
    public static String randomNum(){
      String  result = "";
      String  result2= "";
      for(int i = 1;i <=6; i++)                  //6次執行輸出6個不同字元
            {
            //判斷產生的隨機數是0還是1,是0進入if語句用於輸出數字,是1進入else用於輸出字元
               int rd = Math.random() >= 0.5 ? 1 : 0;   
            
                if(rd == 0)
                    {
                       Random r = new Random();      
                       result = r.nextInt(9) +1 + "";      //產生1-9數字
                 
                    }
                else{
                    //'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
                 char[] A_z = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
                 Random sc = new Random(); 
                 int sub = sc.nextInt(A_z.length);
                 result = A_z[sub] + "";      //產生A——z字元
                
                    }
                 result2 +=result;
            }
    return result2;
            
        
    }
    public static void main(String[] args) {
        System.out.println(randomNum());
    }
    
}