黑马程序员(Java)----API之常用类(Math、Random、System、BigInteger、Date和DateFormat、Calendar)

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

4.9  Math

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

4.9.1 常用变量和方法

成员变量:

public static final double PI

public static final double E

成员方法:

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):最大值 (min自学)

public static double pow(double a,double b):a的b次幂

public static double random():随机数 [0.0,1.0)

public static int round(float a) 四舍五入(参数为double的自学)

public static double sqrt(double a):正平方根

public class MathDemo {
	public static void main(String[] args) {
		//public static final double PI
		System.out.println("PI:"+Math.PI);
		//public static final double E
		System.out.println("E:"+Math.E);
		System.out.println("----------");
		//public static int abs(int a):绝对值
		System.out.println("abs:"+Math.abs(1-3));
		System.out.println("----------");
		//public static double ceil(double a):向上取整
		System.out.println("ceil:"+Math.ceil(12.34));
		System.out.println("----------");
		//public static double floor(double a):向下取整
		System.out.println("floor:"+Math.floor(12.56));
		System.out.println("----------");
		//public static int max(int a,int b):最大值
		System.out.println("max:"+Math.max(12,34));
		System.out.println("----------");
		//public static double pow(double a,double b):a的b次幂
		System.out.println("pow:"+Math.pow(2,3));
		System.out.println("----------");
		//public static double random():随机数 [0.0,1.0)
		System.out.println("random:"+Math.random());
		//获取一个1-100的随机数
		System.out.println("random:"+((int)(Math.random()*100)+1));
		System.out.println("----------");
		//public static int round(float a) 四舍五入
		System.out.println("round:"+Math.round(12.34f));
		System.out.println("round:"+Math.round(12.56f));
		System.out.println("----------");
		//public static double sqrt(double a):正平方根
		System.out.println("sqrt:"+Math.sqrt(4));
	}
}

运行结果:

4.9.2 获得任意范围内的随机数

public class MathDemo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		for (int x = 0; x < 100; x++) {
			System.out.println("请输入开始数:");
			int start = sc.nextInt();
			System.out.println("请输入结束数:");
			int end = sc.nextInt();
			int number = getRandom(start, end);
			System.out.println(number);
		}
	}

	public static int getRandom(int start, int end) {
		// 回想我们获取1-100之间的随机数
		// int number = (int)(Math.random()*100+1);
		int number = (int) (Math.random() * (end - start + 1) + start);
		return number;
	}
}

运行结果:

4.10 Random

构造方法:

public Random():没有种子,用的是默认种子,是当前时间的毫秒值

public Random(long seed):给出指定种子。给定种子后,每次得到的随机数相同的。

成员方法:

public int nextInt():返回的是int范围内的随机数

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

public class RandomDemo {
	public static void main(String[] args) {
		//创建对象
		Random r1 = new Random();
		Random r2 = new Random(1111);
		for(int x = 0;x <5;x++){
			int num = r1.nextInt(100)+1;
			System.out.print(num+" ");
		}
		System.out.println();
		for(int x = 0;x <5;x++){
			int num = r2.nextInt(100)+1;
			System.out.print(num+" ");
		}
	}
}

运行一次后结果:

再次运行后结果:

多次运行后发现r2产生的5个随机数一直是相同的,也就是说给定种子后每次得到的随机数相同的。

4.11 System

System 类包含一些有用的类字段和方法。它不能被实例化。

public static void gc():运行垃圾回收器。

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

		p = null;//让p不在指向堆内存
		System.gc();
	}
}
public class Person {
	private String name;
	private int age;
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		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();
	}
}

运行结果:

执行System.gc()前,系统会自动调用finalize()方法清除对象占有的资源,通过super.finalize()方式可以实现从下到上的finalize()方法的调用,即先释放自己的资源,再去释放父类的资源。

public static long currentTimeMillis():返回以毫秒为单位的当前时间。可用来计算程序运行时间。

public class SystemDemo {
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		for(int x = 0;x <100000;x++){
			System.out.println("hello"+x);
		}
		long end = System.currentTimeMillis();
		System.out.println("共耗时:"+(end-start));
	}
}

运行结果:

public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。

public class SystemDemo {
	public static void main(String[] args) {
		System.out.println("我们喜欢林青霞");
		System.exit(0);
		System.out.println("我们也喜欢赵雅芝");
	}
}

运行结果:

public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length):从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

public class SystemDemo {
	public static void main(String[] args) {
		//	定义数组
		int[] arr = new int[]{11,22,33,44,55};
		int[] arr2 = new int[]{6,7,8,9,10};

		System.arraycopy(arr,1,arr2,2,2);
		System.out.println(Arrays.toString(arr));
		System.out.println(Arrays.toString(arr2));
	}
}

运行结果:

4.12 BigInteger 和 BigDecimal

4.12.1 BigInteger

BigInteger可以让超过Integer范围内的数据进行运算

1、构造方法

BigInteger(String val) :将 BigInteger 的十进制字符串表示形式转换为 BigInteger。

public class BigIntegerDemo {
	public static void main(String[] args) {
		/*Integer i = new Integer(100);
		//System.out.println(Integer.MAX_VALUE);
		Integer ii = new Integer("2147483647");
		Integer iii = new Integer("2147483648");
		System.out.println(i);
		System.out.println(ii);
		System.out.println(iii);*/
		System.out.println(Integer.MAX_VALUE);
		BigInteger bi = new BigInteger("2147483648");
		System.out.println("bi:"+bi);
	}
}

运行结果:

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):返回商和余数的数组

public class BigIntegerDemo {
	public static void main(String[] args) {
		BigInteger bi1 =  new BigInteger("1000");
		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]);
	}
}

运行结果:

4.12.2 BigDecimal

由于在运算的时候,float类型和double很容易丢失精度,例如下面的例子。

public class BigDecimalDemo {
	public static void main(String[] args) {
		System.out.println(0.09 + 0.01);
		System.out.println(1.0 - 0.32);
		System.out.println(1.015 * 100);
		System.out.println(1.301 / 100);

		System.out.println(1.0-0.12);
	}
}

运行结果:

所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal。BigDecimal类:不可变的、任意精度的有符号十进制数,可以解决数据丢失问题。

1、构造方法

public BigDecimal(String val):将 BigDecimal 的字符串表示形式转换为BigDecimal

public class BigDecimalDemo {
	public static void main(String[] args) {
		BigDecimal bd = new BigDecimal("0.09");
		System.out.println(bd);

	}
}

运行结果:

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):商,几位小数,如何舍取

public class BigDecimalDemo {
	public static void main(String[] args) {
		BigDecimal bd1 = new BigDecimal("0.09");
		BigDecimal bd2 = new BigDecimal("0.01");
		System.out.println("add:" + bd1.add(bd2));
		System.out.println("-------------------");

		BigDecimal bd3 = new BigDecimal("1.0");
		BigDecimal bd4 = new BigDecimal("0.32");
		System.out.println("subtract:" + bd3.subtract(bd4));
		System.out.println("-------------------");

		BigDecimal bd5 = new BigDecimal("1.015");
		BigDecimal bd6 = new BigDecimal("100");
		System.out.println("multiply:" + bd5.multiply(bd6));
		System.out.println("-------------------");

		BigDecimal bd7 = new BigDecimal("1.301");
		BigDecimal bd8 = new BigDecimal("100");
		System.out.println("divide:" + bd7.divide(bd8));
		System.out.println("divide:"
				+ bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));
		System.out.println("divide:"
				+ bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));
	}
}

运行结果:

4.13 Date、DateFormat、Calendar

4.13.1 Date

1、构造方法

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

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

import java.util.Date;

public class DateDemo {
	public static void main(String[] args) {
		// 创建对象
		Date d = new Date();
		System.out.println("d:" + d);

		// 创建对象
		// long time = System.currentTimeMillis();
		long time = 1000 * 60 * 60;
		Date d2 = new Date(time);
		System.out.println("d2:" + d2);
	}
}

运行结果:

2、部分常用方法

public long getTime():获取时间,以毫秒为单位

public void setTime(long time):设置时间

import java.util.Date;

/*
 * public long getTime():获取时间,以毫秒为单位
 * public void setTime(long time):设置时间
 */
public class DateDemo {
	public static void main(String[] args) {
		// 创建对象
		Date d = new Date();
		// 获取时间
		long time = d.getTime();
		System.out.println(time);
		System.out.println("d:" + d);
		// 设置时间
		d.setTime(1000);
		System.out.println("d:" + d);
	}
}

运行结果:

学会从Date得到一个毫秒值(建立Date对象,调用getTime()方法),把一个毫秒值转换为Date(使用构造方法或者调用setTime(long time))。

4.13.2 DateFormat

该类包含将日期格式化成文本(Date-->String)的方法,也包含将文本解析成日期(String-->Date)的方法。但是该类是一个抽象类,所以可以通过建立其子类对象来实现。

1、Date-->String

public final String format(Date date):将一个 Date 格式化为日期/时间字符串。

public class DateFormatDemo {
	public static void main(String[] args) throws ParseException {
		//Date-->String
		//创建日期对象
		Date d = new Date();
		//创建默认格式化对象
		SimpleDateFormat sdf = new SimpleDateFormat();
		String s1 = sdf.format(d);
		System.out.println(s1);
		//创建给定模式格式化对象
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
		String s2 = sdf2.format(d);
		System.out.println(s2);
	}
}

运行结果:

2、String-->Date

public Date parse(String source) throws ParseException:从给定字符串的开始解析文本,以生成一个日期。

public class DateFormatDemo {
	public static void main(String[] args) throws ParseException {
		/*//Date-->String
		//创建日期对象
		Date d = new Date();
		//创建默认格式化对象
		SimpleDateFormat sdf = new SimpleDateFormat();
		String s1 = sdf.format(d);
		System.out.println(s1);
		//创建给定模式格式化对象
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
		String s2 = sdf2.format(d);
		System.out.println(s2);*/

		//String-->Date
		String str = "2008-08-08 12:12:12";
		SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dd = sdf3.parse(str);
		System.out.println(dd);
	}
}

运行结果:

练习1:制作一个日期工具类

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 这是日期和字符串相互转换的工具类
 *
 * @author classmate
 *
 */
public class DateUtil {
	private DateUtil(){

	}
	/**
	 * 这个方法的作用就是把日期格式化字符串
	 * @param date	被转换的日期对象
	 * @param format	传递过来的被转换的格式
	 * @return	格式化后的字符串
	 */
	public static String dateToString(Date date,String format){
		/*SimpleDateFormat sdf = new SimpleDateFormat(foramt);
		sdf.format(date);*/
		return new SimpleDateFormat(format).format(date);
	}
	/**
	 * 这个方法的作用就是把字符串解析成一个日期对象
	 * @param s		被解析的字符串
	 * @param format	传递过来的被解析的格式
	 * @return		解析后的日期对象
	 * @throws ParseException
	 */
	public static Date stringToDate(String s,String format) throws ParseException{
		return new SimpleDateFormat(format).parse(s);
	}
}
/*
 * 工具类的测试
 */
public class DateUtilDemo {
	public static void main(String[] args) throws ParseException {
		Date d = new Date();
		//yyyy-MM-dd HH:mm:ss
		String s = DateUtil.dateToString(d, "yyyy-MM-dd HH:mm:ss");
		System.out.println(s);

		String str = "2014-12-12";
		Date dd = DateUtil.stringToDate(str, "yyyy-MM-dd");
		System.out.println(dd);
	}
}

运行结果:

练习2:计算你来到这个世界多少天了

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/*
 * 算一算一个人来到这个世界多少天?
 * 分析:
 * 		A:键盘录入出生日期
 * 		B:把该字符串转换成一个日期
 * 		C:通过该日期得到一个毫秒值
 * 		D:获取当前时间的毫秒值
 * 		E:用D-C得到一个毫秒值
 * 		F:把E的毫秒值转换为年
 * 			/1000/60/60/24
 */
public class MyYearOldDemo {
	public static void main(String[] args) throws ParseException {
		// 录入数据
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入你的出生年月日:");
		String line = sc.nextLine();

		// 把该串转换成一个日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = sdf.parse(line);
		// 通过该日期得到一个毫秒值
		long time = d.getTime();
		// 获取当前时间毫秒值
		long currentTime = System.currentTimeMillis();
		int day = (int) ((currentTime - time) / 1000 / 60 / 60 / 24);
		System.out.println("你来到这个世界:"+day+"天");
	}
}

运行结果:

4.13.3 Calendar

Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。

1、部分方法

public static Calendar getInstance():使用默认时区和语言环境获得一个日历。返回的Calendar 基于当前时间,使用了默认时区和默认语言环境。

public int get(int field):返回给定日历字段的值。日历类中的每个日历字段都是静态的成员变量,并且是int类型。

public void add(int field,int amount):根据给定的日历字段和对应的时间,来对当前的日历进行操作。

public final void set(int year,int month,int date):设置当前日历的年月日

import java.util.Calendar;

public class CalendarDemo {
	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, -3);
		// 获取年
		year = c.get(Calendar.YEAR);
		// 获取月
		month = c.get(Calendar.MONTH);
		// 获取日
		date = c.get(Calendar.DATE);
		System.out.println(year + "年" + (month + 1) + "月" + date + "日");

		// 五年后的10天前
		c.add(Calendar.YEAR, +5);
		c.add(Calendar.DATE, -10);
		// 获取年
		year = c.get(Calendar.YEAR);
		// 获取月
		month = c.get(Calendar.MONTH);
		// 获取日
		date = c.get(Calendar.DATE);
		System.out.println(year + "年" + (month + 1) + "月" + date + "日");

		c.set(2011, 11, 11);
		// 获取年
		year = c.get(Calendar.YEAR);
		// 获取月
		month = c.get(Calendar.MONTH);
		// 获取日
		date = c.get(Calendar.DATE);
		System.out.println(year + "年" + (month + 1) + "月" + date + "日");
	}
}

运行结果:

2、获取任意一年的2月有多少天

import java.util.Calendar;
import java.util.Scanner;

/*
 * 获取任意一年的二月有多少天
 *
 * 分析:
 * 		A:键盘录入任意的年份
 * 		B:设置日历对象的年月、月、日
 * 			年:输入的年份
 * 			月:2//设置为2月,其实为3月
 * 			日:1
 * 		C:把时间往前推一天就是2月的最后一天
 */
public class CalendarTest {
	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);
		int date = c.get(Calendar.DATE);
		System.out.println(date);
	}

}

运行结果:

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-29 08:29:50

黑马程序员(Java)----API之常用类(Math、Random、System、BigInteger、Date和DateFormat、Calendar)的相关文章

黑马程序员--java基础之其他类

-------android培训.java培训.期待与您交流! ---------- Java基础中的其他对象:System 关于System类的用法: /* System:类中的方法和属性都是静态的 out:标准输出,默认是控制台 in:标准输入,默认是键盘 获取系统属性信息:Properties getProperties(); */ import java.util.*; class SystemDemo { public static void main(String[] args) {

黑马程序员——Java基础---反射Class类、Constructor类、Field类

------<a href="http://www.itheima.com" target="blank">Java培训.Android培训.iOS培训..Net培训</a>.期待与您交流! ------- 反射的应用场景 一.概述 反射技术: Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类中的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态调用对象的方法的功能称为java语言的

黑马程序员——Java基础---集合框架工具类

黑马程序员——Java基础<a href="http://www.itheima.com" target="blank">Java培训.Android培训.iOS培训..Net培训</a>.期待与您交流! ------ 一.概述 Java为操作Set.List和Map提供了一系列工具类,主要有Collections和Arrays.这两个工具类的特点:类中的方法都是静态的,不需要创建对象,直接使用类名调用即可.Collections:是集合对象

黑马程序员——Java I/O流基础知识点(File类)

File工具 File类就是用俩将文件或者文件夹封装对象,弥补流对象的不足--流只能操作数据,不能操作文件夹的 封装的是路径!!! 构造方法演示 1.可以将已有的未出现的文件或者文件夹封装成对象. File f1=new File("c:\\abc\\a.txt"): File f2=new File("d:\\abc","ab.txt"打印,会打印路径.:目录分隔符,为了更好地跨平台File. File类常见功能 1,创建 createNewF

黑马程序员——Java集合工具类和泛型

Collections工具类和泛型 Collections和Collection Collections和Collection是不同的,Collections是工具类,用来操作集合的,而Collection是集合接口.Collections中有一系列的静态方法用来操作集合,但是不能更改集合内容.比如不能set()不能remove()元素,可以替换全部元素或者添加同一个元素. static List<String> list =Arrays .asList("one Two three

黑马程序员——Java基础---IO(下)

黑马程序员——Java基础---IO(下) ------<a href="http://www.itheima.com" target="blank">Java培训.Android培训.iOS培训..Net培训</a>.期待与您交流! ------ 一.概述 Java除了基本的字节流.字符流之外,还提供了File类.properties类.打印流.序列流等和输入输出相关的类,它们能够帮助我们更好的处理信息.下面将对它们进行简单的介绍. 一.正

黑马程序员——java高新---注解、泛型等

------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- 一.注解 什么是注解? 答:对于过时的语句,java会提示过时了,通过@SuppressWarnings("Deprecation")可以在DOS命令行中取消提示,但Eclipse无法取消.这就是注解,相当于标记.编译器.开发工具.javac通过反射获得注解里的内容,进而明确应该做什么.不应该做什么.注解可以加在包.类.属性.方法.参数及局部变量之上.一个注解就是一个类. java.

黑马程序员——java基础---IO(input output)流字符流

黑马程序员——java基础---IO(input output)流字符流 ------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- io(input output)流特点: 1,io流用来处理数据之间的传输 2,java对数据的操作是通过流的方式: 3,java用于操作流的对象都在io包中: 4,流按操作数据分为两种:字节流和字符流: 5,流按流向分为:输入流和输出流. 注意:流只能操作数据,而不能操作文件. 3.IO流的常用基类: 1)字节流的抽象

黑马程序员---Java多线程

---------------------- Android开发.java培训.期待与您交流! ---------------------- 线程与进程是程序运行中体现的两个名词,它包含这不同的程序域.进程指的是一个正在运行的程序,如:360,QQ运行时就是不同的两个进程.当你打开windows任务管理器时,看到的每个进程就是此时windows中正在运行的程序.线程则就是进程中的一个个独立的控制单元,线程控制着进程的执行,也就是说每个正在运行的程序中就包括着很多的线程. 主线程:Java虚拟机运

黑马程序员——java基础——反射

 黑马程序员--java基础--反射 ------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- 反射 其实就是动态加载一个指定的类,并获取该类中的所有的内容.而且将字节码文件封装成对象,并将字节码文件中的内容都封装成对象,这样便于操作这些成员. 反射就是把Java类中的各种成分映射成相应的java类. 简单说:反射技术可以对一个类进行解剖. 反射的基石-->Class类 1.java中的类是用来描述一类事物的共性,该类事物有什么属性,没有什么属性