13-系统常用类2
13-系统常用类2
一般来说,如果我们要使用数字的话,会考虑使用基本数据类型(内置数据类型)。然而,实际开发过程中,我们经常会遇到需要使用对象,而不是内置数据类型的情形。为了解决这个问题,Java 语言为每一个内置数据类型提供了对应的包装类。
所有的包装类(Integer、Long、Byte、Double、Float、Short)都是抽象类 Number 的子类。由编译器特别支持的包装称为装箱,所以当内置数据类型被当作对象使用的时候,编译器会把内置类型装箱为包装类。相似的,编译器也可以把一个对象拆箱为内置类型。Number 类属于 java.lang 包。
Number中的基本类型&包装类型
- 八大基本数据类型也有对应的包装类:(wrapper class )
boolean --> Boolean char --> Character byte --> Byte short ---> Short
- int --> Integer long --> Long float --> Float double --> Double
八个基本数据类型都重写了Object中的hashCode(), equals(), toString()方法。
Integer inObj = new Integer(10);
System.out.println(inObj);
int i = inObj.intValue();
System.out.println(i);
String stri = String.valueOf(i); //String.valueOf(任何数据类型);
System.out.println(stri);
int inti = Integer.parseInt("100");
System.out.println(inti);
- 常用方法:
public static void main(String[] args) {
// 包装类 --> 基本数据类型 =>将 Number对象转换为xxx数据类型的值并返回。
Integer ii = new Integer(30);
System.out.println("compareTo="+ii.compareTo(40)); //compareTo=1 大于 -1 小于 0相等
System.out.println("equals判断包装类参数是否:"+ii.equals(30));
Character c = new Character('国');
System.out.println("Character c = 国");
System.out.println("是否是字母:" + Character.isLetter(c));
System.out.println("是否是数字:" + Character.isDigit(c));
System.out.println("是否是字母或数字" + Character.isLetterOrDigit(c));
System.out.println("isLowerCase:" + Character.isLowerCase('a'));
System.out.println("isUpperCase:" + Character.isUpperCase('A'));
System.out.println("isSpaceChar(char ch)判断字符 是否是个 空格 字符:" + Character.isSpaceChar(' '));
补充:
因为浮点型 运算结果具有精确度不准确,所以一般地,涉及于金钱或者精度要求较高的计算,不用浮点类型计算。采用 Number类的子类 BigDecimal中的有参构造函数
// BigDecimal进行转化
BigDecimal bigDecimal1 = new BigDecimal("0.3");
BigDecimal bigDecimal2 = new BigDecimal("3");
// 通过BigDecimal实现+-*/
System.out.println("bigDecimal1=" + bigDecimal1);
BigDecimal add = bigDecimal1.add(bigDecimal2);
System.out.println("add=" + add);
BigDecimal mul = bigDecimal1.multiply(bigDecimal2);
System.out.println("mul=" + mul);// 0.9
BigDecimal sub = bigDecimal1.subtract(bigDecimal2);
System.out.println("sub=" + sub);
BigDecimal div = bigDecimal1.divide(bigDecimal2);
System.out.println("div=" + div);
Math数学函数类
java.lang.Math 类(无需导包)包含基本的数字操作,如指数、对数、平方根和三角函数;Math中方法和常量都是静态的,因此可以通过类名直接调用。
常量
static double E
static double PI 的 double值比其他任何接近零圆周率,圆周和直径的比值。
public class Test {
public static void main (String []args)
{
System.out.println("90 度的正弦值:" + Math.sin(Math.PI/2));
System.out.println("0度的余弦值:" + Math.cos(0));
System.out.println("60度的正切值:" + Math.tan(Math.PI/3));
System.out.println("1的反正切值: " + Math.atan(1));
System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI/2));
System.out.println(Math.PI);
}
}
常用的方法
static double abs(double a); //有重载方法 绝对值
static double ceil(double a); //有重载方法 大于等于
static double floor(double a); //有重载方法 小于等于
static long round(double a); //有重载方法 四舍五入
static double pow(double a, double b); //次方
static double random();//随机数
static double max(double a,double b);//求更大值
static double min(double a,double b);//求更小值
public static void main(String[] args) {
double[] nums = { 1.4, 1.5, 1.6, -1.4, -1.5, -1.6 };
for (double num : nums) {
test(num);
}
}
private static void test(double num) {
System.out.println("Math.floor(" + num + ")=" + Math.floor(num));
System.out.println("Math.round(" + num + ")=" + Math.round(num));
System.out.println("Math.ceil(" + num + ")=" + Math.ceil(num));
}
Number与Math 类常用的一些方法
序号 | 方法与描述 |
---|---|
1 | xxxValue() 将 Number 对象转换为xxx数据类型的值并返回。 |
2 | compareTo() 将number对象与参数比较。 结果: 1 大于 0相等 -1 小于 |
3 | equals() 判断number对象是否与参数相等。 |
4 | valueOf() 返回一个 Number 对象指定的基本数据类型 |
5 | toString() 以字符串形式返回值。 |
6 | parseInt() 将字符串解析为int类型。 |
7 | abs() 返回参数的绝对值。 |
8 | ceil() 返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。 |
9 | floor() 返回小于等于(<=)给定参数的最大整数 。 |
10 | rint() 返回与参数最接近的整数。返回类型为double。 |
11 | round() 它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。 |
12 | min() 返回两个参数中的最小值。 |
13 | max() 返回两个参数中的最大值。 |
14 | exp() 返回自然数底数e的参数次方。 |
15 | log() 返回参数的自然数底数的对数值。 |
16 | pow(double value, double n) 返回第一个参数的第二个参数次方。 |
17 | sqrt(double value) 求参数的算术平方根。 |
18 | sin() 求指定double类型参数的正弦值。 |
19 | cos() 求指定double类型参数的余弦值。 |
20 | tan() 求指定double类型参数的正切值。 |
21 | asin() 求指定double类型参数的反正弦值。 |
22 | acos() 求指定double类型参数的反余弦值。 |
23 | atan() 求指定double类型参数的反正切值。 |
24 | atan2() 将笛卡尔坐标转换为极坐标,并返回极坐标的角度值。 |
25 | toDegrees() 将参数转化为角度。 |
26 | toRadians() 将角度转换为弧度。 |
27 | random() 返回一个随机数。随机数范围为 0.0 =< Math.random < 1.0 |
随机数Random
产生随机数的方式有两种, 一种是Math类中的random(), 另一种是java.util.Random类。
Math的random方法
Math类中的random()返回 带正号的 double 值,该值大于等于 0.0 且小于 1.0。
- 获取0到10之间的随机整数的方法是:
double d1 = Math.random() * 10;
int in1 = Math.round(d1);
//或用下面的方法:
double d2 = Math.random() * 11;
int in2 = (int)d2;
random类
java.util.Random中存在两个构造函数Random(); Random(long seed);
- 1.在没带参数构造函数生成的Random对象的种子缺省是当前系统时间的毫秒数
- 2.对于种子相同的Random对象,生成的随机数序列是一样的。
- 常用方法: 获取随机数值: next整型数据类型() 方法返回为该整型数据类型
/**
* 构造函数 有两种:无参和有参 ::
* 1.在没带参数构造函数生成的Random对象的种子缺省是当前系统时间的毫秒数
* 2.对于种子相同的Random对象,生成的随机数序列是一样的。
* 常用方法: 获取随机数值: next整型数据类型() 方法返回为该整型数据类型
* @author wyn
*
*/
public class TestRandom {
public static void main(String[] args) {
TestRandom tr =new TestRandom();
// tr.test1();
tr.test2();
}
//无参构造函数Random()
public void test1() {
Random r =new Random();
//nextInt() 随机产生 0~9的数
for(int i =0; i<20; i++) { //nextInt(参数) 返回一个int型的 <参数 整型随机数, 若为空,则返回int型的范围值 int a = r.nextInt(10); System.out.println("随机产生 0~9的数:"+a); } //获取1-10之间的随机数 for(int i =0; i<20; i++) { int num = r.nextInt(10)+1; System.out.println("获取1-10之间的随机数:"+num); } //获取0-10之间的随机数 for(int i =0; i<20; i++) { int num = r.nextInt(11); System.out.println("**获取1-10之间的随机数:"+num); } } //有参构造函数 种子数 public void test2() { Random ran1 = new Random(10); System.out.println("使用种子为10的Random对象生成[0,10)内随机整数序列: "); for (int i = 0; i < 10; i++) { System.out.print(ran1.nextInt(10) + " "); } System.out.println(); Random ran2 = new Random(10); System.out.println("使用另一个种子为10的Random对象生成[0,10)内随机整数序列: "); for (int i = 0; i < 10; i++) { System.out.print(ran2.nextInt(10) + " "); } } ``` - 其他用法: - 生成[0,1.0)区间的小数: double d1 = r.nextDouble(); - 生成[0,5.0)区间的小数: double d2 = r.nextDouble() * 5; - 生成[1,2.5)区间的小数: double d3 = r.nextDouble() * 1.5 + 1; - 生成-231到231-1之间的整数: int n = r.nextInt(); - 生成[0,10)区间的整数: ```java int n2 = r.nextInt(10);//方法一 n2 = Math.abs(r.nextInt() % 10);//方法二
日期相关类
系统时间获取
long System.currentTimeMillis();
//返回以ms毫秒为单位的当前时间,返回当前时间与 1970 年 1 月 1 日午夜之间的时间差(以毫秒为单位测量)
//这个方法常用计算一段代码所发的时间;
long start = System.currentTimeMillis();
// 中间为一段程序段
long end = System.currentTimeMillis();
long diff = end - start;//程序段执行所用时间
Date类 常用来表示日期时间
子类:java.sql.Date:用于Java程序处理数据库中日期字段的年月日
java.sql.Time:用于Java程序处理数据库中日期字段的时分秒
java.sql.TimeStamp:用于Java程序处理数据库中日期字段的年月日时分秒毫秒
- 常用构造方法:
- Date()
- Date(long date)
- 常用方法:
- boolean after(Date when);
- boolean before(Date when);
- String toString();
例子:Date应用
private static void testDate() {
// Date:表示某一个特定的瞬间
// java.sql.Date
// java.util.Date
Date date = new Date();
System.out.println("date=" + date);
System.out.println(date.getTime());// 1537185242840
int year = date.getYear();
System.out.println("year=" + year);
// 获取月份时要+1
int month = date.getMonth();
System.out.println("month=" + month);
int day = date.getDay();
int date2 = date.getDate();
System.out.println("day=" + day);
System.out.println("date2=" + date2);
// Date start = new Date();
// for (int i = 0; i < 999999L; i++) {
// System.out.println("i=" + i);
// }
// Date end = new Date();
// System.out.println(end.getTime()-start.getTime());
//
// after
// before
Date when = new Date();
Date history = new Date(15371852428L); //long
System.out.println(history.before(when));// true
System.out.println(history.after(when));// false
}
日期格式化
DateFormat抽象类提供了格式化日期的方法,SimpleDateFormat是它的简单实现类。
可以将日期格式化成指定格式的字符串;也可将指定格式字符串格式化为日期;
SimpleDateFormat类中模式字符:
- y 年Year -->1996; 96
- M 年中的月份 Month July; Jul; 07
- d 月份中的天数 Number 10
- E 星期中的天数 Text Tuesday; Tue
- H 一天中的小时数(0-23) Number 0
- h am/pm 中的小时数(1-12) Number 12
- m 小时中的分钟数 Number 30
- s 分钟中的秒数 Number 55
- S 毫秒数
例子: 日期格式化DateFormat
// DateFormat是抽象类,其实现子类是SimpleDateFormat,主要用对日期进行格式化,
// 可以将日期跟字符串进行互相转换
/*
* SimpleDateFormat类中模式字符: y 年 Year 1996; 96 M 年中的月份 Month July; Jul; 07 d
* 月份中的天数 Number 10 E 星期中的天数 Text Tuesday; Tue H 一天中的小时数(0-23) Number 0 h
* am/pm中的小时数(1-12) Number 12 m 小时中的分钟数 Number 30 s 分钟中的秒数 Number 55 S 毫秒数
*/
String pattern = "yyyy-MM-dd HH:mm:ss";
DateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = new Date();
System.out.println("转换之前的Date对象=" + date);
// 将时间转换成指定格式的字符串
String time = dateFormat.format(date);
System.out.println("time=" + time);
// 字符串转成时间
String myTime = "2019-01-01 00:00:12";
Date myDate = null;
try {
myDate = dateFormat.parse(myTime);
} catch (ParseException e) {//报错原因格式化,如果字符串没有按给定的规范来就会才会报错。
e.printStackTrace();
}
System.out.println("myDate=" + myDate);
//例子 你来到这个世界多少天了
String birthday= "1998年6月14日";
String today= "2020年6月14日";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
Date d1 = sdf.parse(birthday);
Date d2 = sdf.parse(today);
//d1与d2相差 返回long型 毫秒
long time = d2.getTime()-d1.getTime();
System.out.println(time / 1000 / 60 / 60 /24 +"天");
System.out.println(time / 1000 / 60 / 60 /24 /365 +"年");
日历类:Calendar
- Calendar 类是一个抽象类,用于描述一个日历。这个类不能直接初始化,但有个类方法getInstance() 用于创建Calendar对象。
static Calendar getInstance();
int get(int field);
Date getTime()
int get(int field);
void set(int field, int value);
void setTime(Date date);
void setTimeInMillis(long millis);
static int YEAR
static int MONTH // 取得的月要加1;因为月从0开始
static int DAY_OF_MONTH
static int HOUR_OF_DAY
static int HOUR
static int MINUTE
static int SECOND
static int DAY_OF_WEEK // 星期日为一个星期的第一天,索引从1开始。
private static void testCalendar() {
// Calendar日历类是一个抽象类
Calendar calendar = Calendar.getInstance();
System.out.println("calendar=" + calendar);
// 获取日历对象的年份、月份、。。。。
int year = calendar.get(Calendar.YEAR);
System.out.println("year=" + year);
int month = calendar.get(Calendar.MONTH);
System.out.println("month=" + month);
int weekOfYear = calendar.get(3);
int weekOfYear2 = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("weekOfYear=" + weekOfYear);
System.out.println("weekOfYear2=" + weekOfYear2);
//转成成Date
Date date = calendar.getTime();
System.out.println("date="+date);
}
精度计算
BigDecimal: 可以用在金钱 、价格
double 浮点型是不能用在具有精确度高的 价格或者是其他的
BigDecimal add(BigDecimal augend); // +
BigDecimal subtract(BigDecimal subtrahend); // -
BigDecimal multiply(BigDecimal multiplicand); // *
BigDecimal divide(BigDecimal divisor); // /
BigDecimal setScale(int newScale, int roundingMode);
static int ROUND_HALF_UP
public static void main(String[] args) {
// 对浮点数进行运算会产生精度的损失
// 计算在存储数据是采用二进制形式来存储:所以0.3用二进制表示:
// 所以0.3用二进制表示:01001100100110011001.......
// 计算机不会用无限的内存来存储该数值
// 0.3*2 = 0.6 0
// 0.6*2 = 1.2 1
// 0.2*2 =0.4 0
// 0.4*2=0.8 0
// 0.8*2 = 1.6 1
// 0.6*2 =1.2 1
// 0.5的二进制表示0.1
// 0.5*2=1.0 1
// 0.0*2 =0
double d = 0.3;
System.out.println("d=" + d);
System.out.println("d*3=" + d * 3);// 0.8999999999
// 如何进行避免
// BigDecimal进行转化
BigDecimal bigDecimal1 = new BigDecimal("0.3");
BigDecimal bigDecimal2 = new BigDecimal("3");
// 通过BigDecimal实现+-*/
System.out.println("bigDecimal1=" + bigDecimal1);
BigDecimal add = bigDecimal1.add(bigDecimal2);
System.out.println("add=" + add);
BigDecimal mul = bigDecimal1.multiply(bigDecimal2);
System.out.println("mul=" + mul);// 0.9
BigDecimal sub = bigDecimal1.subtract(bigDecimal2);
System.out.println("sub=" + sub);
BigDecimal div = bigDecimal1.divide(bigDecimal2);
System.out.println("div=" + div);
//将BigDecimal转成double
double d1 = div.doubleValue();
System.out.println("d1="+d1);
}
数字格式化
NumberFormat 是所有数字格式的抽象基类。此类提供了格式化和分析数字的接口;
static NumberFormat getInstance()
void setMaximumFractionDigits(int newValue)
void setMaximumIntegerDigits(int newValue)
void setMinimumFractionDigits(int newValue)
void setMinimumIntegerDigits(int newValue)
String format(long number)
Number parse(String source)
//创建一个默认的通用格式
NumberFormat numberFormat = NumberFormat.getInstance();
DecimalFormat numberDecimalFormat;
//捕捉异常,以防强制类型转换出错
try {
//强制转换成DecimalFormat
numberDecimalFormat = (DecimalFormat) numberFormat;
//保留小数点后面三位,不足的补零,前面整数部分 每隔四位 ,用 “,” 符合隔开
numberDecimalFormat.applyPattern("#,####.000");
//设置舍入模式 为DOWN,否则默认的是HALF_EVEN
numberDecimalFormat.setRoundingMode(RoundingMode.DOWN);
//设置 要格式化的数 是正数的时候。前面加前缀
numberDecimalFormat.setPositivePrefix("Prefix ");
System.out.println("正数前缀 "+numberDecimalFormat.format(123456.7891));
//设置 要格式化的数 是正数的时候。后面加后缀
numberDecimalFormat.setPositiveSuffix(" Suffix");
System.out.println("正数后缀 "+numberDecimalFormat.format(123456.7891));
//设置整数部分的最大位数
numberDecimalFormat.setMaximumIntegerDigits(3);
System.out.println("整数最大位数 "+numberDecimalFormat.format(123456.7891));
//设置整数部分最小位数
numberDecimalFormat.setMinimumIntegerDigits(10);
System.out.println("整数最小位数 "+numberDecimalFormat.format(123456.7891));
//设置小数部分的最大位数
numberDecimalFormat.setMaximumFractionDigits(2);
System.out.println("小数部分最大位数 "+numberDecimalFormat.format(123.4));
//设置小数部分的最小位数
numberDecimalFormat.setMinimumFractionDigits(6);
System.out.println("小数部分最小位数 "+numberDecimalFormat.format(123.4));
}catch (Exception e){
e.printStackTrace();
}
获取百分比格式 货币格式
//创建一个中国地区的 百分比格式
NumberFormat perFormat = NumberFormat.getPercentInstance(Locale.CHINA);
DecimalFormat percentFormat;
try {
percentFormat = (DecimalFormat) perFormat;
//设置Pattern 会使百分比格式,自带格式失效
// percentFormat.applyPattern("##.00");
//设置小数部分 最小位数为2
percentFormat.setMinimumFractionDigits(2);
System.out.println(percentFormat.format(0.912345));
} catch (Exception e) {
e.printStackTrace();
}
//货币格式
//创建一个中国地区的 货币格式
NumberFormat curFormat = NumberFormat.getCurrencyInstance(Locale.CHINA);
DecimalFormat currencyFormat;
try {
currencyFormat = (DecimalFormat) curFormat;
//设置Pattern 会使百分比格式,自带格式失效
// currencyFormat.applyPattern("##.00");
System.out.println(currencyFormat.format(0.912345));
//乘法 数乘以多少 这个方法是 百分比时候 设置成100 km时候 是1000
currencyFormat.setMultiplier(100);
System.out.println(currencyFormat.format(0.912345));
} catch (Exception e) {
e.printStackTrace();
}
DecimalFormat
DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字。该类设计有各种功能;
- 常用构造方法:
DecimalFormat()
DecimalFormat(String pattern)
- 常用方法:
String toPattern()
void applyPattern(String pattern)
String format(double d); //有重载方法