📜  Java中的 BigInteger intValueExact() 方法及示例(1)

📅  最后修改于: 2023-12-03 15:01:51.028000             🧑  作者: Mango

Java中的 BigInteger intValueExact() 方法及示例

介绍

BigInteger 是Java中的一个类,用于处理任意长度的整数。 intValueExact()BigInteger 类的一个方法,用于将 BigInteger 的值转换为int类型。如果转换结果超出了int类型的范围,则会抛出 ArithmeticException 异常。该方法比 intValue() 方法更为严格。

语法
public int intValueExact() throws ArithmeticException
参数

没有参数。

返回值

BigInteger 的值转换为int类型。

异常
  • ArithmeticException - 当转换结果超出int类型范围时。
示例
import java.math.BigInteger;

public class Example {
    public static void main(String[] args) {
        BigInteger bigInt = new BigInteger("12345678901234567890");

        try {
            int intValue = bigInt.intValueExact();
            System.out.println("intValue of bigInt: " + intValue);
        } catch (ArithmeticException e) {
            System.out.println("Conversion result out of range");
        }
    }
}

输出结果:

Conversion result out of range

在此示例中,我们首先创建一个 BigInteger 对象 bigInt,其值为“12345678901234567890”。然后,我们尝试使用 intValueExact() 方法将其转换为 int 类型。由于转换结果超出了int类型的范围,因此会抛出 ArithmeticException 异常,我们在 catch 块中捕获并输出异常信息。