【JavaSE】其他常用类:Math、Random、Calendar、System

@

一、Math类

1.1 成员变量

  • public static final double PI
  • public static final double E

1.2 成员方法

  • public static int abs(int a):绝对值
  • public static double ceil(double a):向上取整
  • public static double floor(double a):向下取整
  • public static int round(float a) 四舍五入(参数为double的自学)
  • public static int max(int a,int b):最大值 (min自学)
  • public static double pow(double a,double b):a的b次幂
  • public static double random():随机数 [0.0,1.0)
  • public static double sqrt(double a):正平方根

1.3 案例练习:任意两数之间的随机整数

/**
 * 任意两数之间的随机整数
 */
public class RabdomeDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入开始数字:");
        int start = sc.nextInt();
        System.out.println("请输入结束数字:");
        int end = sc.nextInt();

        for (int i= 0; i < 5; i++){
            int random = getRandom(start, end);
            System.out.println(random);
        }
    }
    public static int getRandom(int start ,int end){

      // int random = (int) (Math.random()*100 + 1);//1~100之间的整数
        int random = (int) (Math.random()*(end - start +1) + start);
       return random;

    }

}

二、Randm类

2.1 构造方法

  • public Random():没有给种子,用的是默认种子,是当前时间的毫秒值
  • public Random(long seed):给出指定的种子

2.2 成员方法

  • public int nextInt():返回的是int范围内的随机数
  • public int nextInt(int n):返回的是[0,n)范围的内随机数

2.3 案例练习


三、Calendar类

Calendar(JDK1.1之后,抽象类)

得到子类对象:

Calendar rightNow = Calendar.getInstance();

方法

int year = rightNow.get(Calendar.YEAR);
int month = rigthNow.get(Calendar.MONTH);
int date = rightNow.get(Calendar.DATE);

add()和set()

public void add(int field, int amount) //:根据给定的日历字段和对应的时间,来对当前的日历进行操作。
public final void set(int year, int month, int date) //:设置当前日历的年月日

Date getTime():返回的是Date,不是毫秒值

long getTimeInMills()

案例:获取任意年份的2月份有多少天

public class CalendarTest02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入年份:");
        int year = sc.nextInt();

        Calendar c = Calendar.getInstance();
        c.set(year,2,1); // 其实是这一年的3月1日
        c.add(Calendar.DATE,-1);// 把时间往前推一天,就是2月的最后一天
        // 获取这一天输出即可
        System.out.println(c.get(Calendar.DATE));
    }
}
public class CalendarTest {
    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);
        System.out.println(year + "/" + (month+1) + "/" + date);


        //十年前的今天
        c.add(Calendar.YEAR ,- 10);
        int year10 = c.get(Calendar.YEAR);
        int month10 = c.get(Calendar.MONTH);
        int date10 = c.get(Calendar.DATE);
        System.out.println(year10 + "/" + (month10+1) + "/" + date10);

        //五年后的今天
        c.add(Calendar.YEAR ,5);
        int year5 = c.get(Calendar.YEAR);
        int month5 = c.get(Calendar.MONTH);
        int date5 = c.get(Calendar.DATE);
        System.out.println(year5 + "/" + (month5+1) + "/" + date5);

    }

}

四、格式化问题

4.1 SimpleDateFormat(实现类)

4.2 构造方法

  • SimpleDateFormat():默认模式
  • SimpleDateFormat(String pattern):给定的模式

4.3 方法实现字符串和日期的互相转换

Date→String

Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String s = sdf.format(d);

String→Date

String str = "2008-08-08 12:12:12";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(str);

4.2 日期工具类的编写

public class DateUtil {

    public static void main(String[] args) throws ParseException {
        String dateStr = dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");
        System.out.println(dateStr);

        Date date = stringToDate("2020/5/10 19:45:05", "yyyy/MM/dd HH:mm:ss");
        System.out.println(date.toString());
    }
    /**
     * 把日期转成一个字符串
     */
    public static String dateToString(Date date,String format){
        return new SimpleDateFormat(format).format(date);
    }
    /**
     * 把一个字符串解析成一个日期对象
     */
    public static Date stringToDate(String s, String format) throws ParseException {
        return new SimpleDateFormat(format).parse(s);
    }
}

4.3 案例:你来到世界多少天

/**
 * 你来到世界多少天
 * 你还能活多少天
 */
public class MyDayOld {
    public static void main(String[] args) throws ParseException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的出生年月日:");
        String line = sc.nextLine();
        System.out.println("请输入你会活到多少岁:");
        long x = sc.nextLong();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date myDate = sdf.parse(line);


        long myTime = myDate.getTime();//获取我的生日时的毫秒值
        long nowTime = System.currentTimeMillis();//获取当下的毫秒值

        long time = nowTime - myTime;
        long day = time / 1000 / 60 / 60 / 24;
        System.out.println("你来到这个世界:" + day + "天");



        Date endDate = myDate;
        endDate.setTime(myTime + (x * 365  * 24 * 60 * 60 * 1000));
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String endStr = sdf2.format(endDate);

        System.out.println("还可以活到 " + endStr);

        long endTime = endDate.getTime();
        long time2 = endTime - nowTime;
        long day2 = time2 / 1000 / 60 / 60 / 24;
        System.out.println("你还能活:" + day2 + "天");

    }
}

五、Date(JDK1.1之前)

5.1 构造方法

  • Date():根据当前的默认毫秒值创建日期对象
  • Date(long date):根据给定的毫秒值创建日期对象

5.2 方法

把一个毫秒值转换为Date

  • 构造方法:Date(long date)
  • setTime(long time)

六、BigDecimal

float和double类型在计算时很容易丢失精度。为了能精确表示、计算浮点数Java提供了BigDecimal
很容易丢失精度,但不是一定.PNG

在这里插入图片描述

6.1 构造方法

  • public BigDecimal(String val)

6.2 成员方法

  • public BigDecimal add(BigDecimal augend)

  • public BigDecimal subtract(BigDecimal subtrahend)

  • public BigDecimal multiply(BigDecimal multiplicand)

  • public BigDecimal divide(BigDecimal divisor)

  • public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)
    在这里插入图片描述

七、BigInteger

可以让超出Integer范围的数据进行计算

7.1 构造方法

(只讲一个):public BigInteger(String val)

7.2 成员方法

public BigInteger add(BigInteger val)

public BigInteger subtract(BigInteger val)

public BigInteger multiply(BigInteger val)

public BigInteger divide(BigInteger val)

public BigInteger[] divideAndRemainder(BigInteger val)

import java.math.BigInteger;

/*
 * public BigInteger add(BigInteger val):加
 * public BigInteger subtract(BigInteger val):减
 * public BigInteger multiply(BigInteger val):乘
 * public BigInteger divide(BigInteger val):除
 * public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组
 */
public class BigIntegerDemo {
	public static void main(String[] args) {
		BigInteger bi1 = new BigInteger("100");
		BigInteger bi2 = new BigInteger("50");

		// public BigInteger add(BigInteger val):加
		System.out.println("add:" + bi1.add(bi2));
		// public BigInteger subtract(BigInteger val):加
		System.out.println("subtract:" + bi1.subtract(bi2));
		// public BigInteger multiply(BigInteger val):加
		System.out.println("multiply:" + bi1.multiply(bi2));
		// public BigInteger divide(BigInteger val):加
		System.out.println("divide:" + bi1.divide(bi2));

		// public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组
		BigInteger[] bis = bi1.divideAndRemainder(bi2);
		System.out.println("商:" + bis[0]);
		System.out.println("余数:" + bis[1]);
	}
}

八、System

  • public static void gc():运行垃圾回收器
public class Person {
	private String name;
	private int age;

	public Person() {
		super();
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

	@Override
	protected void finalize() throws Throwable {
		System.out.println("当前的对象被回收了" + this);
		super.finalize();
	}

}

public class SystemDemo {
	public static void main(String[] args) {
		Person p = new Person("赵雅芝", 60);
		System.out.println(p);

		p = null; // 让p不再指定堆内存
		System.gc();
	}
}

注:走 System.gc(); 之前,先走 final ,先释放自己的资源,再释放父类的资源

  • public static void exit(int status) 终止当前运行的Java虚拟机,参数为状态码

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

  • public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) 从指定原数组中复制一个数组
    在这里插入图片描述

原文地址:https://www.cnblogs.com/popo33/p/13221861.html