Java常用类之Math类Random类和System类

Math类

  1、概述
   Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
  2、成员变量
  public static final double E : 自然底数
  public static final double PI: 圆周率
  3、成员方法
  public static int abs(int a) 取绝对值
  public static double ceil(double a) 向上取整
  public static double floor(double a) 向下取整
  public static int max(int a,int b) 获取最大值
  public static int min(int a, int b) 获取最小值
  public static double pow(double a,double b) 获取a的b次幂
  public static double random() 获取随机数 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
  public static int round(float a) 四舍五入
  public static double sqrt(double a)获取正平方根

注意导正确的包
mport static java.lang.Integer.min;
import static java.lang.Math.*;
import static java.lang.StrictMath.floor;
import static sun.swing.MenuItemLayoutHelper.max;

public class Test {
    public static void main(String[] args) {
        int a = abs(-5); //a=5;
        double b =ceil(3.9); //b=4.0
        double c = floor(3.9); //c=3.0
        int d = max(3, 5); //d=5,注意参数必须为int型
        int e = min(3, 5); //e=3,注意参数必须为int型
        double f = pow(2, 3); // f=8.0,注意参数和返回值都为double型
        double random = random();//返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
        long gL = round(4.5); //gL=5,注意返回值为long型
        double h = sqrt(9); //h=3.0,注意返回值为double型
    }
}

  

Random类

  1、概述
   此类用于产生随机数如果用相同的种子创建两个 Random 实例,
   则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列
  2、构造方法
  public Random() 没有给定种子,使用的是默认的(当前系统的毫秒值)
  public Random(long seed) 给定一个long类型的种子,给定以后每一次生成的随机数是相同的
  3、成员方法
  public int nextInt()//没有参数 表示的随机数范围 是int类型的范围
  public int nextInt(int n)//可以指定一个随机数范围
  void nextBytes(byte[] bytes) 生成随机字节并将其置于用户提供的空的 byte 数组中。

import java.util.Arrays;
import java.util.Random;
public class Test {
    public static void main(String[] args) {
        Random random = new Random();
        int i = random.nextInt(); //int类型的范围,-2^31~2^31-1
        int j = random.nextInt(10); //范围0~9
        byte[] bytes=new byte[10];
        random.nextBytes(bytes);  //生成随机字节并将其置于用户提供的空的 byte 数组中,字节的范围是byte类型的范围-127~128
        System.out.println(Arrays.toString(bytes));
    }
}

System类

  1、概述
   System 类包含一些有用的类字段和方法。它不能被实例化。
  2、成员方法
  public static void gc()//调用垃圾回收器
  public static void exit(int status)//退出java虚拟机 0 为正常退出 非0为 异常退出
  public static long currentTimeMillis()//获取当前时间的毫秒值


原文:https://blog.csdn.net/qq_40763549/article/details/89817825

猜你喜欢

转载自www.cnblogs.com/qbdj/p/10856089.html