java随机数,短信验证码

1、在日常开发中经常用到随机数,或在多线程测试的等待中经常用随机毫秒数;

2、先举例java中常用的两种最基本的生成随机数的方法;

3、读者可以根据实际情况,在两种基本方法上衍生或扩展,比如生辰6位固定随机数(短信验证码)等。

1、两种最基本的随机数生成方式举例:

package com.liuxd.random;

import java.util.Random;

/**
 * Created by Liuxd on 2018/9/5.
 */
public class TestRandom {
    public static void main(String[] args) {


        Random random = new Random();

        int num1 = random.nextInt(1000);

        System.out.println("使用Random类,生成随机数:" + num1);
        System.out.println("------------------------");

        int num2 = (int) (Math.random() * 1000);

        System.out.println("使用Math类,生成随机数:" + num2);


    }
}

2、6位短信验证码举例

package com.liuxd.random;

/**
 * Created by Liuxd on 2018/9/5.
 */
public class TestRandom {


    public static String getCode1() {

        Integer intFlag = (int) (Math.random() * 1000000);

        String flag = intFlag.toString();

        if (flag.length() == 6 && flag.startsWith("9")) {
            return intFlag.toString();
        } else {
            intFlag = intFlag + 100000;
            return intFlag.toString();
        }


    }

    public static String getCode2() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(getCode1());
        }

        System.out.println("---------------------------------");

        for (int i = 0; i < 10; i++) {
            System.out.println(getCode2());
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春风化作秋雨

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值