Math类
Math类包含执行基本数组运算的方法,但是在Math类中的方法都是静态的,调用方法需要Math.方法
| 方法名 | 说明 |
|---|---|
| public static int abs(int a) | 返回参数的绝对值 |
| public static double ceil(double a) | 返回大于或等于参数的最小double值,等于一个整 数 |
| public static double floor(double a) | 返回小于或等于参数的最大double值,等于一个整 数 |
| public static int round(floor a) | 按照四舍五入返回最接近参数的int |
| public static int max(int a,int b) | 返回两个int值中的较大值 |
| public static int min(int a,int b) | 返回两个int值中的较小值 |
| public static int pow(double a,double b) | 返回a的b次幂的值 |
| public static double random() | 返回值为double的正值,[0.0,1.0) |
代码实例
//abs(int a)
int a = -1;
int b = Math.abs(a);
System.out.print(b);// 1
//ceil(double a)
double a = 1.1;
double b = Math.ceil(a);
System.out.print(b);// 2.0
//floor(double a)
double a = 1.1;
double b = Math.floor(a);
System.out.print(b);// 1.0
//round(floor a)
floor a = 1.4345f;
floor d = 1.5345f;
int b = Math.round(a);
int c = Math.round(d);
System.out.print(b);// 1
System.out.print(c);// 2
//max(int a,int b)
int a = 4;
int b = 5;
int c = Math.max(a,b);
System.out.print(c);// 5
//min(int a,int b)
int a = 4;
int b = 5;
int c = Math.min(a,b);
System.out.print(c);// 4
System类
| 方法名 | 说明 |
|---|---|
| public static void exit(int status) | 终止当前运行的 Java 虚拟机,非零表示异常终止 |
| public static long currentTimeMillis() | 返回当前时间(以毫秒为单位 |
代码示例
public static void main(){
//获取开始的时间点
long start = System.currentTimeMillis();
for(int i = 1;i <= 1000;i++){
System.out.print(i);
}
//获取代码运行结束后的时间节点
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end ‐ start) + "毫秒");
}
Date类
Date类的构造方法
| 方法名 | 说明 |
|---|---|
| public Date() | 分配一个 Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒 |
| public Date(long date) | 分配一个 Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数 |
代码示例
public static void main(String[] args){
//获得当前时间节点
Date d1 = new Date();
System.out.print(d1);
//获得指定时间
long time = 1000*60*60;
Date d2 = new Date(time);
System.out.print(d2);
}
Date类常用方法
| 方法名 | 说明 |
|---|---|
| public long getTime() | 获取的是日期对象从1970年1月1日 00:00:00到现在的毫秒值 |
| public void setTime(long time) | 设置时间,给的是毫秒值 |
代码示例
public static void main(String[] args){
//创建日期对象
Date date = new Date();
//将date数据转换成毫秒值
long time1 = date.getTime();
System.out.print(time1);
long time2 = System。currentTimeMillis();
date.setTime(time2);
Syetem.out.print(date);
}
SimpleDateFormat类
SimpleDateFormat类概述 SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期SimpleDateFormat类构造方法
Date类常用方法
| 方法名 | 说明 |
|---|---|
| public SimpleDateFormat() | 构造一个SimpleDateFormat,使用默认模式和日期格式 |
| public SimpleDateFormat(String pattern) | 构造一个SimpleDateFormat使用给定的模式和默认的日期 格式 |
代码示例
public static void main(String[] args){
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(simpleDateFormat.parse(date));
}
本文详细介绍了Java中的Math类,包括绝对值、取整、四舍五入等基本数学运算方法;System类的exit()和currentTimeMillis()方法;Date类的构造与时间操作,以及如何通过SimpleDateFormat进行日期格式化。通过代码实例展示了每个方法的使用方式,帮助读者深入理解Java基础操作。
1万+

被折叠的 条评论
为什么被折叠?



