Java基础之随机数

目录

1 Math类

2 Random类

3 一个不会重复的随机数-UUID类

1 Math类

        Math类是Java中封装数学公式的工具类。

ceil():>=的整数

floor():<=的整数

rint():最近的整数,0.5返回0

round():四舍六入的整数,0.5特殊

常量PI:圆周率π,double数据类型

public class MathMethod {
  public static void main(String[] args) {
    //abs方法,取绝对值
    System.out.println(Math.abs(3.14)); //3.14
    System.out.println(Math.abs(0));  //0
    System.out.println(Math.abs(-2.2)); //2.2
 
    //ceil方法,向上取整,往大的靠
    System.out.println(Math.ceil(3.8)); //4.0
    System.out.println(Math.ceil(-3.2)); //-3.0
     
    //floor方法,向下取整,往小的靠
    System.out.println(Math.floor(3.2)); //3.0
    System.out.println(Math.floor(-3.8)); //-4.0
 
    //round方法,四舍 六入 五成双
    //先看看四舍六入,如果出现负数,先转成正数,再四舍六入,最后加上负号
    System.out.println(Math.round(3.4)); //3
    System.out.println(Math.round(3.6)); //4
    System.out.println(Math.round(-3.4)); //-3
    System.out.println(Math.round(-3.6)); //-4
    //五成双是出现0.5结尾的时候,就给它再加上+0.5,5不就成双了
    //接着再对相加的结果进行floor运算
    System.out.println(Math.round(-2.5)); //-2
    System.out.println(Math.floor(-2.5 + 0.5)); //与Math.round(-2.5)结果一致
    System.out.println(Math.round(2.5)); //3
    System.out.println(Math.floor(2.5 + 0.5)); //与Math.round(2.5)结果一致

    System.out.println("PI 常量的值: " +Math.PI);
  }
}

        double Math.random() 静态方法,获取随机数,返回值范围[0,1) 。

double random = Math.random();

        在[1,10]之间随机产生一个数值运算过程:

        [1,10]  => [0,9]+1  => [0,9] ((int)Math.random() * 10)

公式:[a,b] => [0,b-a]+a  => (int)( Math.random() * (b-a+1) ) + a

2 Random

public int nextInt(int bound)

        返回伪随机的,均匀分布int值介于0(含)指定值(不包括)

public static void main(String[] args) {
    Random random = new Random();
    //[1,10]
    int i = random.nextInt(10)+1;
    System.out.println(i);
    //[2,10] => [0,10-2]+2
    int j = random.nextInt(9)+2;
    System.out.println(j);
}

3 一个不会重复的随机数-UUID类

public static void main(String[] args) {
    UUID uuid = UUID.randomUUID();//随机的唯一标识符
    System.out.println(uuid);

    String goodsId = uuid.toString().replace("-","");
    System.out.println(goodsId);
}

        封装的工具类:

public class UUIDUtils {
    public static String getUUID(){
        UUID uuid = UUID.randomUUID();//随机的唯一标识符
        return uuid.toString().replace("-","");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值