生成隨機數字和字母

 //生成隨機數字和字母, 
    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; 
    }app

 

//生成隨機的數字
    Random rnd = new Random(); 
    public String getRandomNumber(int digCount) { 
        StringBuilder sb = new StringBuilder(digCount); 
        for(int i=0; i < digCount; i++) 
            sb.append((char)('0' + rnd.nextInt(10))); 
        return sb.toString(); 
    }dom

相關文章
相關標籤/搜索