java如何随机生成定长的字符串

2021-06-18 23:06

阅读:496

标签:ilo   csdn   row   and   abc   static   https   copy   parse   

小数,字符串、时间等示例代码

public class RandomTest {

    public static Random rand = new Random();
    public static String dateStart = "2017-01-01 00:00:00";
    /**
     * hh 表示12小时制
     * HH 表示24小时制
     */
    public static SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
    public static SimpleDateFormat format1 = new SimpleDateFormat("YYYYMMDDHHmmss");


    public static void main(String[] args) throws ParseException {
        System.out.println(getDouble());

        long timeStart = 1483200000000l;
        System.out.println(format.parse(dateStart).getTime());

        System.out.println(format.format(new Date(timeStart)));
        System.out.println(format.format(new Date(timeStart+1000)));
        System.out.println(format.format(new Date(timeStart+2000)));

        format.format(new Date());

        System.out.println(getRandomString(2));

    }
    /**
     * 随机生成指定精确度的小数
     * @return
     */
    public static double getDouble(){
        DecimalFormat df=new DecimalFormat("#.000000");
        int a=(int)(Math.random()*2+1);
        int aa=(int)(Math.pow(-1, a));

        return Double.valueOf(df.format(rand.nextDouble()*100*aa));
    }
    /**
     * 生成固长字符串
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   
        Random random = new Random();   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i int number = random.nextInt(base.length());   
            sb.append(base.charAt(number));   
        }   
        return sb.toString();   
     }  
    /**
     * 生成固长字符串
     * @param length
     * @return
     */
    public static String getRandomStringNum(int length) { //length表示生成字符串的长度
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
        Random random = new Random();   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i int number = random.nextInt(base.length());   
            sb.append(base.charAt(number));   
        }   
        return sb.toString();   
    }
}

--------------------- 本文来自 AngelaPotato 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/wangxilong1991/article/details/72636482?utm_source=copy 

java如何随机生成定长的字符串

标签:ilo   csdn   row   and   abc   static   https   copy   parse   

原文地址:https://www.cnblogs.com/YuyuanNo1/p/9705810.html


评论


亲,登录后才可以留言!