生成隨機數

                                         生成隨機數

 做一串8位隨機數包含大寫字母和兩個數字

 

public class Test22 {
    public static void main(String[] args) {
        System.out.println(getRundom());
    }
    public static String getRundom(){
        StringBuffer id=new StringBuffer();
        id.append("XY");
        Random random = new Random();
        int index =0;
        for (int i = 0; i < 6; i++) {
            char s = 0;
            int j=random.nextInt(2) % 4;
            if(index ==2){
                j = 1;
            }
            switch (j) {
                case 0:
                    //隨機生成數字
                    ++index;
                    s = (char) (random.nextInt(57) % (57 - 48 + 1) + 48);
                    break;
                case 1:
                    //隨機生成大寫字母
                    s = (char) (random.nextInt(90) % (90 - 65 + 1) + 65);
                    break;
                    default:
            }
            id.append(s);
        }
        return id.toString();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章