2Java面向对象编程——6java核心类——6常用工具类(廖雪峰)

1.Math类

Math提供了数学计算的静态方法:

  • abs/min/max
  • pow/sqrt/exp/log/log10
  • sin/cos/tan/asin/acos...

常量:

  • PI=3.14159...
  • E=2.71828

2.Random

Math.random()生产一个随机数:

  • 0<=随机数<1
  • 可用于生成某个区间的随机数
//0<=R<1
double x1 = Math.random();

//MIN <= R < MAX
long MIN = 1000;
long MAX = 9000;
double x2 = Math.random()*(MAX - MIN)+MIN;
double r = (long)x2;

Random用来创建伪随机数

  • nextInt/nextLong/nextFloat...
  • nextInt(N)生成不大于N的随机数
Random r = new Random();
r.nextInt();//生成下一个随机int
r.nextLong();//生成下一个随机long
r.nextFloat();//生成下一个随机float,介于0~1
r.nextDouble();//生成下一个随机double,介于0~1

r.nextInt(10);//生成0~10之间的随机数,不包括10

什么是伪随机数?

  • 给定种子后伪随机数算法会生成完全相同的序列
  • 不给定种子时Random使用系统当前时间戳作为种子
Random r = new Random(12345);
for(int i = 0; i < 10; i++){
    System.out.println(r.nextInt(100));
}
//51,80,41,28,...

SecureRandom用来创建安全的随机数,缺点是比较慢

SecureRandom sr = new SecureRandom();
for(int i = 0; i < 10; i++){
    System.out.println(sr.nextInt(100));
}

3.BigInterger

BigInterger用任意多个int[]来表示非常大的整数

BigInteger bi = new BigInteger("1234567890");
System.out.println(bi.pow(5));

4.BigDecimal

BigDecimal表示任意精度的浮点数

BigDecimal bd = new BigDecimal("123.10");
System.out.println(bd);
public class Main {
	
	public static void main(String[] args){
		//Math
		System.out.println(Math.sqrt(2));
		
		//Random
		Random rnd = new Random(123456);
		System.out.println(rnd.nextInt());
		System.out.println(rnd.nextInt());
		
		//SecureRandom
		SecureRandom sr = new SecureRandom();
		System.out.println(rnd.nextInt());
		System.out.println(rnd.nextInt());
		
		//BigInteger
		BigInteger bi = new BigInteger("1234567890");
		System.out.println(bi.pow(5));
		
		//BigDecimal
		BigDecimal bd = new BigDecimal("123.10");
		System.out.println(bd.multiply(bd));
	}
}

总结

JDK常用工具类

  • Math:数学计算
  • Random:生成伪随机数
  • SecureRandom:生成安全的随机数
  • BigInteger:表示任意大小的整数
  • BigDecimal:表示任意精度的浮点数
  • BigInteger和BigDecimal都继承自Number

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小夏天禧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值