Java獲取隨機數驗證碼,例454670(短信驗證碼,郵箱驗證碼)

package com.wy.project.utils.eamil;

import java.util.Random;

/**
獲取隨機驗證碼

@author Administrator
*/
public class RandomCode {
public static String getRandStr(int charCount) {
String charValue = “”;
for (int i = 0; i < charCount; i++) {
char c = (char) (randomInt(0, 26) + ‘a’);
charValue += String.valueOf(c);
}
return charValue;
}

public static String getRandNum(int charCount) {
    String charValue = "";
    for (int i = 0; i < charCount; i++) {
        char c = (char) (randomInt(0, 10) + '0');
        charValue += String.valueOf(c);
    }
    return charValue;
}

public static int randomInt(int from, int to) {
    Random r = new Random();
    return from + r.nextInt(to - from);
}

package com;

import java.net.MalformedURLException;

public class Test {

/**
 * @param args
 * @throws MalformedURLException 
 */
public static void main(String args[]) throws MalformedURLException {

    //參數表示輸出隨機數的位數
    //getRandNum()返回的是數字隨機數,getRandStr()返回的字母隨機數
    System.out.println(RandomCode.getRandNum(6));
}

}

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