常用随机数工具类

来源:互联网 发布:手机改图软件 编辑:程序博客网 时间:2024/06/09 16:23
import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;public class RandomUtil {    /**     * 生成一个n位的随机数字符串     *      * @param n     * @return     */    public static String getRandomNum(int length) {        String str = "0123456789";        Random random = new Random();        StringBuffer sb = new StringBuffer();        for (int i = 0; i < length; ++i) {            int number = random.nextInt(10);// [0,10)            sb.append(str.charAt(number));        }        return sb.toString();    }    /**     * 生成一个n位的随机字符串     *      * @param length     * @return     */    public static String getRandomString(int length) {        String str = "abcdefghijklmnopqrstuvwxyz0123456789";        Random random = new Random();        StringBuffer sb = new StringBuffer();        for (int i = 0; i < length; ++i) {            int number = random.nextInt(36);// [0,36)            sb.append(str.charAt(number));        }        return sb.toString();    }    /**     * 获取当前时间,年月日时     *      * @return     */    public static String getDate() {        String str = "";        DateFormat df = new SimpleDateFormat("yyyyMMddHH");        Date date = new Date();        str = df.format(date);        return str;    }    /**     * 生成用户id,10位,纯数字     *      * @return     */    public static String userId() {        String userId = "";        userId = getRandomNum(10);        return userId;    }    /**     * 生成订单号,13位,纯数字     *      * @return     */    public static String orderId() {        String orderId = "";        String date = getDate();        String rand = getRandomNum(13);        orderId = date + rand;        return orderId;    }    /**     * 生成商品id,10位,纯数字     *      * @return     */    public static String proId() {        String userId = "";        userId = getRandomNum(10);        return userId;    }}
0 0
原创粉丝点击