java 随机生成4位随机数

java 随机生成4位的随机数测试类

@org.junit.Test
public void testRandom(){
String msg="您的注册码为%s,谢谢注册!";

System.out.println("Math.random得到小数");
System.out.println(Math.round((Math.random()+1) * 1000));
System.out.println("Random");
System.out.println(new Random().nextInt(9999));
System.out.println("字符串前面补0的话就这样String.format");
System.out.println(String.format("%04d",new Random().nextInt(9999)));
}

注意:Math.random()方法结果可能会是0,所以进行了 +1 操作。

 输出结果:

Math.random得到小数

6644
Random
5413
字符串前面补0的话就这样String.format
2714

posted @ 2019-07-01 15:24  明天,你好啊  阅读(52057)  评论(5编辑  收藏  举报