常用的辅助类1(输入输出、包装类、Math、Random、BigInteger、BigDecimal)

Java知识点总结:想看的可以从这里进入

7、常用的API


7.1、输入输出

7.1.1、Scanner

Scanner类是Java中的一个实用类,用于从各种输入流(如控制台输入、文件输入、字符串输入等)中读取数据。它是Java标准库的一部分,位于java.util包中。

  1. 导入 Scanner 类:import java.util.Scanner;

  2. 创建 Scanner对象:Scanner scanner = new Scanner(System.in);

  3. 使用 Scanner对象的方法读取数据:

    • next():读取下一个单词(以空格为分隔符)。

    • nextLine():读取整行输入

    • nextInt():读取下一个整数。

    • nextDouble():读取下一个双精度浮点数。

    • nextBoolean():读取布尔值

7.1.2、System

System 是 Java 中的一个 final 类,位于 java.lang 包中。它提供了一些与系统相关的标准输入、标准输出、错误输出流,以及访问外部定义的属性和环境变量的方法。

System 提供了 标准输入 in、标准输出 out、错误输出 err 这几种类变量,

  • System.in:标准输入流,默认连接到键盘输入。

  • System.out:标准输出流,默认连接到控制台输出。

  • System.err:标准错误输出流,默认连接到控制台输出。

    // 输出到控制台
    System.out.println("Hello, world!");
    

并提供了一些静态方法用于访问环境变量、系统属性的方法,在Java17时又为System 新增加 native.encoding 属性用于获取操作系统的字符集。除此之外System 还提供了加载文件和动态链接库的方法。

  • currentTimeMillis():返回以毫秒为单位的当前时间。

    long currentTime = System.currentTimeMillis();
    
  • exit(int status):终止当前运行的 Java 虚拟机。status 非零表示异常终止。

    System.exit(0);
    
  • gc():请求运行垃圾收集器。虽然不能保证立即发生垃圾回收,但可以增加其发生的可能性。

    System.gc();
    
  • getenv(String name):获取指定环境变量的值。

    String path = System.getenv("PATH");
    
  • getProperty(String key):根据键名获取系统属性。

    String javaVersion = System.getProperty("java.version");
    
  • setProperty(String key, String value):设置或更新一个系统属性。。

    System.setProperty("myKey", "myValue");
    
  • arraycopy(Object src, int srcPos, Object dest, int destPos, int length):从指定源数组中复制一个数组,从指定位置开始,到目标数组的指定位置。

    int[] src = {1, 2, 3, 4, 5};
    int[] dest = new int[5];
    System.arraycopy(src, 0, dest, 0, 5);
    
  • setErr(PrintStream err) 和 setOut(PrintStream out):重新分配 “标准” 错误输出流和输出流。

    System.setOut(new PrintStream(new FileOutputStream("log.txt")));
    

7.2、包装类

在Java中有八种基本数据类型,这些基本数据类型不支持面向对象的机制,也不具备对象的特性,虽然基本数据类型在使用时很方便,但有些时候也会有一些制约,所以Java特地为基本数据类型封装了对应的包装类。

在这里插入图片描述

7.2.1、整数类

在这里插入图片描述

Integer和int的区别:

int是8中基本数据之一,Integer是java为基本数据类型int提供的封装类。他们具有不同的特征和用法。
1、大小:int在内存栈,占用4字节,存储速度快。Integer在内存堆上,空间大速度慢。
2、默认值:int为0,Integer为null,可以区分未赋值和值为0的区别,而int不能。
3、Integer是提供的类,所以内部提供了一些方法和属性。
4、int主要用在计算中,而Integer用在类型转换、向集合中存取数据。提供的方法

整形包装类使用valueOf方法创建整数时,可以使用其缓存机制。数值在-128~127之间时,不会创建新对象,而是直接引用常量池中的已经创建好的对象。在Integer中定义了一个IntegerCache结构,此结构中定义个一个Integer[] cache,用来保存-128~127,所以在此范围内是不需要new新对象的。

Integer i1 = 100, i2 = 100, i3=200, i4=200;
i1和i2共用一个对象,i3和i4使用不同对象

在这里插入图片描述

7.2.2、布尔值

image-20240426153057415

7.2.3、浮点型

在这里插入图片描述

7.2.4、字符型

image-20240426153024536

7.2.5、自动拆、装箱

在JDK1.5之前,基本数据类型和包装类之间需要主动使用对应的方法来互相转换,但是这样有些繁琐,所以在JDK1.5 后Java提供了自动拆箱、自动装箱的功能。

  • 自动装箱:自动将基本数据类型变为包装类对象。
  • 自动拆箱:自动将包装类中包装的基本数据类型取出。

自动装箱时编译器会主动调用 valueOf 将原始类型值转换成对象,自动拆箱时,编译器会通过调用类似 intValue()、
doubleValue() 这类的方法将对象转换成原始类型值。(装箱和拆箱是编译器要做的工作,而不是虚拟机。编译器生成类的字节码时会插入必要的方法调用,而虚拟机只是执行这些字节码。)

所以自动拆箱和自动装箱并不是不需要相应的方法进行转化,而是这些转换的方法在底层中自动调用,不再需要我们主动去写。但是在使用时需要注意类型是否匹配。

image-20210202170809896

image-20240426143358115

7.3、Math 类

包含了用于执行基本数学运算的属性和方法,如初等指数、对数、平方根和三角函数。Math 是一个工具类,所以内部的方法都被定义为 static 形式,通过 Math 类可以在主函数中直接调用。

  1. 基本运算:

    • abs:返回参数的绝对值。

    • Math.addExact(num1,num2):对两个整数进行加法运算,并检查溢出。

    • Math.subtractExact(num1,num2):对两个整数进行减法运算,并检查溢出。

    • Math.multiplyExact(num1,num2):对两个整数进行乘法运算,并检查溢出。

    • Math.floorDiv(num1,num2):对两个整数进行除法运算,并检查溢出。

    • Math.floorMod(num1,num2):取模

    • incrementExact、decrementExact:对整数进行自增或自减运算,并检查溢出。

    public static void main(String[] args) {
        System.out.println(Math.addExact(5, 10));  		//加  15
        System.out.println(Math.subtractExact(10, 5));  // 减 5
        System.out.println(Math.multiplyExact(5, 2));   // 乘 10
        System.out.println(Math.floorDiv(10, 3));  		// 除 3
        System.out.println(Math.floorMod(10, 3));  		// 取模 1
        System.out.println(Math.incrementExact(5)); 	// 自增 6
        System.out.println(Math.decrementExact(5));  	// 自减 4
        System.out.println(Math.abs(-5));  				// 绝对值 5
    }
    
  2. 幂、指数和对数

    • Math.pow(num1,num2):计算第一个参数的第二个参数次幂。

    • Math.sqrt(num):计算参数的平方根。

    • Math.cbrt(num):计算参数的立方根。

    • Math.exp(num):计算自然数 e 的参数次幂。

    • log、log10:分别计算自然对数和以10为底的对数。

    public static void main(String[] args) {
        //pow, sqrt, cbrt, exp, log, log10, log1p
        System.out.println(Math.pow(2, 3));   //2的3次方  8.0
        System.out.println(Math.sqrt(9));     //开平方 3.0
        System.out.println(Math.cbrt(8));     //开立方 2.0
        System.out.println(Math.exp(1));    //自然对数  2.718281828459045
        System.out.println(Math.log(Math.E));   //e的对数  1.0
        System.out.println(Math.log10(Math.E)); //10的对数 0.4342944819032518
        System.out.println(Math.log1p(Math.E)); //1+e的对数  1.3132616875182228
    }
    
  3. 三角函数和角度转换

    • sin、cos、tan:计算角度(以弧度为单位)的正弦、余弦、正切值。

    • asin、acos、atan、atan2:计算反三角函数值。

    • toDegrees、toRadians:角度和弧度之间的转换。

    System.out.println(Math.sin(Math.PI/2));    //正弦  
    System.out.println(Math.cos(Math.PI/2));    //余弦
    System.out.println(Math.tan(Math.PI/2));    //正切
    System.out.println(Math.asin(1));           //反正弦
    System.out.println(Math.acos(1));           //反余弦
    System.out.println(Math.atan(1));           //反正切
    System.out.println(Math.atan2(1, 1));       //反正切
    System.out.println(Math.toDegrees(Math.PI/2));  //将弧度转换为角度
    System.out.println(Math.toRadians(180));    //将角度转换为弧度
    
  4. 四舍五入和取整

    • round:四舍五入到最接近的整数。

    • floor:向下取整到最接近的整数。

    • ceil:向上取整到最接近的整数。

    • rint:返回最接近参数的整数值。在某些情况下,可能会偏向于偶数。

    public static void main(String[] args) {
    	System.out.println(Math.round(3.5));    //四舍五入 4
        System.out.println(Math.round(3.4));    //四舍五入 3
        System.out.println(Math.ceil(3.5));     //向上取整 4.0
        System.out.println(Math.ceil(3.4));     //向上取整 4.0
        System.out.println(Math.floor(3.5));    //向下取整 3.0
        System.out.println(Math.floor(3.4));    //向下取整 3.0
        System.out.println(Math.rint(3.5));     //四舍五入 4.0
        System.out.println(Math.rint(3.4));     //四舍五入 3.0
    }
    
  5. 随机数

    • random:返回一个0.0到1.0之间的随机浮点数。

      System.out.println(Math.random());
      
  6. 最大值和最小值

    • max、min:分别返回两个参数中的最大值和最小值。

      System.out.println(Math.max(1, 2)); //获取最大值 2
      System.out.println(Math.min(1, 2)); //获取最小值 1
      

Math 类在Java标准库中提供了一系列高效、易用的数学计算方法。这些方法广泛应用于科学计算、数据分析、工程设计等领域。使用这些方法时,通常只需直接调用静态方法即可,无需事先创建对象或进行复杂配置。

7.4、随机数类

7.4.1、Random类

Random类用于生成一个伪随机。

常用方法:

image-20220831144824607

7.5、大数

在 Java 中,当标准的数据类型(如 doublelong)的大小不足以存储大数值时,可以使用 BigIntegerBigDecimal 这两个类,它们能处理包含任意长度数字序列的数值。BigInteger 实现任意精度的整数运算。BigDecimal实现任意精度的浮点数运算。

7.8.1、BigInteger

BigInteger 类位于 java.math 包内,在 Java 中代表一个不可变的任意精度的整数,它提供了一系列方法来进行大整数的算术运算、位操作、比较、哈希码计算等。由于 BigInteger 操作的成本比原生类型(如 intlong)要高,因此它通常在需要非常大的整数或者标准数据类型无法满足需求时使用。

image-20231110143416414

import java.math.BigInteger;
public class BigIntegerExample {
    public static void main(String[] args) {
        BigInteger bigInt1 = new BigInteger("12345678901234567890");
        BigInteger bigInt2 = new BigInteger("98765432109876543210");

        BigInteger sum = bigInt1.add(bigInt2);  // 加法
        BigInteger difference = bigInt1.subtract(bigInt2);  // 减法
        BigInteger product = bigInt1.multiply(bigInt2); // 乘法
        BigInteger quotient = bigInt2.divide(bigInt1);  // 除法
        BigInteger power = bigInt1.pow(2);  // 幂运算
        int i = bigInt1.compareTo(bigInt2);         //比较大小
        //求最大值,最小值
        BigInteger max = bigInt1.max(bigInt2);
        BigInteger min = bigInt1.min(bigInt2);

        // 输出结果
        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
        System.out.println("Product: " + product);
        System.out.println("Quotient: " + quotient);
        System.out.println("Power: " + power);
        System.out.println("比较大小:"+i);
        System.out.println("最大值:"+max);
        System.out.println("最小值:"+min);
    }
}

在这里插入图片描述

  • BigInteger 是不可变的,每次操作都会返回一个新的 BigInteger 实例。
  • BigInteger 的运算成本比原生类型高,因此应当在需要处理大数时才使用。
  • 在进行除法运算时,如果除数为零,会抛出 ArithmeticException
  • BigInteger 不支持原生类型的运算符重载,如 +-*/,必须使用相应的方法进行运算。
7.5.2、BigDecimal

BigDecimal 是 Java 中的一个类,用于精确的浮点数计算,它属于 java.math 包,提供了用于算术、比较、格式化、哈希码计算等的操作。

其在 Java 中代表了一个不可变的、任意精度的有符号十进制数,它非常适合用于需要高精度计算的场景,如金融领域的货币计算。

1public BigDecimal(String val); // 通过字符串创建 BigDecimal 推荐使用
2public BigDecimal(double val);	// 通过double创建,不推荐使用,会产生精度丢失。如果需要使用double作为参数创建,推荐使用BigDecimal valueOf(double val)。
3public BigDecimal(BigInteger val);	//通过 BigInteger 创建 BigDecimal
4publicBigDecimal(BigInteger, int);//通过BigInteger,并指定小数点位数
5BigDecimal.valueOf(int);	//通过 int 或 long 构造

其中BigDecimal类提供了一些用于运算的方法:

  1. 算数运算

    算术运算方法
    1、加法:BigDecimal add(BigDecimal); // 加上另一个BigDecimal并返回结果。
    2、减法:BigDecimal subtract(BigDecimal); // 从这个BigDecimal减去另一个并返回结果。
    3、乘法:BigDecimal multiply(BigDecimal); // 与另一个BigDecimal相乘并返回结果。
    4、除法:BigDecimal divide(BigDecimal, int, RoundingMode); // 指定结果的小数位数和舍入模式。
    		BigDecimal divide(BigDecimal, RoundingMode); // 除以BigDecimal,指定舍入模式。
    		BigDecimal divide(BigDecimal); // 除以BigDecimal,结果的精度需要外部管理以避免无限小数。
    		BigDecimal divideToIntegralValue(BigDecimal, MathContext); // 进行除法运算,只取整数部分。
    		BigDecimal[] divideAndRemainder(BigDecimal); // 进行除法运算并返回结果中的整数部分和余数。
    		BigDecimal divideToIntegralValue(BigDecimal); // 进行除法运算并只取整数部分。
    5、求余数:BigDecimal remainder(BigDecimal); // 返回余数。
    6、四舍五入:BigDecimal multiply(BigDecimal, MathContext); // 与另一个BigDecimal相乘,使用MathContext对象指定精度和舍入模式。
    7、幂运算:BigDecimal pow(int); // 将此BigDecimal的值提升到指定的幂并返回结果。
       幂运算并指定上下文:BigDecimal pow(int, MathContext); // 将此BigDecimal的值提升到指定的幂,使用MathContext对象指定精度和舍入模式。
    8、绝对值:BigDecimal abs(); // 返回此BigDecimal的绝对值。
    9、负值:BigDecimal negate(); // 返回此BigDecimal的负数形式。
    10、正值:BigDecimal plus(); // 返回一个数学上等价的BigDecimal,通常用于获取精确的正数形式。
    
  2. 舍入和精度控制方法

    1、设置小数位数:BigDecimal setScale(int, RoundingMode); // 设置小数点后的位数,并指定舍入模式。
    2、设置小数位数:BigDecimal setScale(int, int); // 设置小数点后的位数,舍入模式使用整数表示。
    
  3. 比较方法

    1、比较两个BigDecimalint compareTo(BigDecimal); //当两个BigDecimal值相同时,返回0
    2、判断是否相等:boolean equals(Object x); // 检查此BigDecimal是否与另一个对象数值上相等
    
  4. 转换方法

    1、转换为 doubledouble doubleValue();
    2、转换为 floatfloat floatValue();
    3、转换为 longlong longValue(); 
    4、转换为 intint intValue(); 
    5、转换为 shortshort shortValueExact(); //精确转换为short,如果有信息丢失则抛出异常。
    6、转换为 bytebyte byteValueExact(); // 精确转换为byte,如果有信息丢失则抛出异常。
    7、转换为长整型(精确):long longValueExact(); // 精确转换为long,如果有信息丢失则抛出异常。
    8、转换为整型(精确):int intValueExact(); // 精确转换为int,如果有信息丢失则抛出异常。
    
  5. 工具方法

    1BigDecimal max(BigDecimal);  //最大值
    2BigDecimal min(BigDecimal);  //最小值
    3、求最大公约数:BigDecimal gcd(BigDecimal); // 计算此BigDecimal与另一个BigDecimal的最大公约数。
    4、移位操作:BigDecimal shiftLeft(int n); // 将此BigDecimal的数值左移指定的位数。
    		   BigDecimal shiftRight(int n); // 将此BigDecimal的数值右移指定的位数。
    
  6. 其他方法

    1、返回小数点后的位数:int scale(); 
    2、返回整数部分的位数:int precision();3、返回非零部分的最低位的指数:int getLowestSetBit(); // 返回此BigDecimal二进制表示中最低位的非零位。
    4int signum(); // 返回此BigDecimal的符号,-1表示负数,0表示零,1表示正数。
    5、判断是否为质数可能性:boolean isProbablePrime(int certainty);
    6、判断 BigDecimal 是否为零:boolean isZero(); 
    7、判断是否为负数:boolean isNegative(); 
    8、判断是否为正数:boolean isPositive(); 
    

需要注意的是使用BigDecimal 时判断两个BigDecimal 的值是否相等是,不应该使用equals,因为equals不仅需要数值相同,小数的位数也需要相同,即 2 和 2.0 最后结果为不相等。此时需要使用compareTo()方法,。

  • 使用字符串构造器创建 BigDecimal 是最安全的方式,可以避免由于 double 的不精确表示而导致的问题。
  • 在进行除法时,如果无法整除,需要提供舍入模式,否则可能会抛出 ArithmeticException
  • BigDecimal 是不可变的,每次操作都会返回一个新的 BigDecimal 实例。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

辰 羽

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

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

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

打赏作者

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

抵扣说明:

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

余额充值