目录
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("-","");
}
}