Java常用API(二)Random,System与Math

79 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第11天,点击查看活动详情

Random

用于生成随机数。

使用步骤:

  1. 导入包:import java.util.Random

  2. 创建对象:Random r = new Random()

  3. 随机整数:int num = r.nextInt(20)

    • 解释:20 代表的是一个范围,括号写 20 的随机数则是 0 - 19
    • 获取 0 - 10:int num = r.nextInt(10 + 1)
  4. 随机小数:public double nextDouble() 从范围 0.0d 至 1.0d (左闭右开),随机地生成并返回

System

System 代表当前系统

静态方法:

  • public static void exit(int status):终止 JVM 虚拟机,非 0 是异常终止

  • public static long currentTimeMillis():获取当前系统此刻时间毫秒值

  • static void arraycopy(Object var0, int var1, Object var2, int var3, int var4):数组拷贝

    • 参数一:原数组
    • 参数二:从原数组的哪个位置开始赋值
    • 参数三:目标数组
    • 参数四:从目标数组的哪个位置开始赋值
    • 参数五:赋值几个
public class SystemDemo {
    public static void main(String[] args) {
        //System.exit(0); // 0代表正常终止!!
        long startTime = System.currentTimeMillis();//定义sdf 按照格式输出
        for(int i = 0; i < 10000; i++){输出i}
		long endTime = new Date().getTime();
		System.out.println( (endTime - startTime)/1000.0 +"s");//程序用时

        int[] arr1 = new int[]{10 ,20 ,30 ,40 ,50 ,60 ,70};
        int[] arr2 = new int[6]; // [ 0 , 0 , 0 , 0 , 0 , 0]
        // 变成arrs2 = [0 , 30 , 40 , 50 , 0 , 0 ]
        System.arraycopy(arr1, 2, arr2, 1, 3);
    }
}

Math

Math 用于做数学运算

Math 类中的方法全部是静态方法,直接用类名调用即可:

方法说明
public static int abs(int a)获取参数a的绝对值
public static double ceil(double a)向上取整
public static double floor(double a)向下取整
public static double pow(double a, double b)获取 a 的 b 次幂
public static long round(double a)四舍五入取整
public static int max(int a,int b)返回较大值
public static int min(int a,int b)返回较小值
public static double random()返回值为 double 的正值,[0.0,1.0)
 public class MathDemo {
     public static void main(String[] args) {
         // 1.取绝对值:返回正数。
         System.out.println(Math.abs(10));
         System.out.println(Math.abs(-10.3));
         // 2.向上取整: 5
         System.out.println(Math.ceil(4.00000001)); // 5.0
         System.out.println(Math.ceil(-4.00000001));//4.0
         // 3.向下取整:4
         System.out.println(Math.floor(4.99999999)); // 4.0
         System.out.println(Math.floor(-4.99999999)); // 5.0
         // 4.求指数次方
         System.out.println(Math.pow(2 , 3)); // 2^3 = 8.0
         // 5.四舍五入 10
         System.out.println(Math.round(4.49999)); // 4
         System.out.println(Math.round(4.500001)); // 5
         System.out.println(Math.round(5.5));//6
     }
 }