从BigInteger类型添加(long)的方法不可见

时间:2017-10-05 18:16:34

标签: java biginteger

如何向BigInteger添加任何数字?我在日食中遇到这个错误: -

The method add(long) from the type BigInteger is not visible

import java.math.BigInteger;

public class M  {
    public static void main(String[] args) {
        BigInteger a =  new BigInteger("20000423242342342354857948787922222222222388888888888888888");
        System.out.println("" + (a.add(2));
    }
}

3 个答案:

答案 0 :(得分:1)

您无法将正常整数添加到BigInteger

但您可以将BigInteger添加到另一个BigInteger。所以你应该将原始整数转换为BigInteger,如下所示:

System.out.println(b.add(BigInteger.valueOf(2)));

答案 1 :(得分:1)

如果查看BigInteger的源代码,您将看到一个用于添加长数值的重载方法。但他们也在方法描述中提到该方法是私有的。这就是为什么你无法从班上打电话的原因。

/**
     * Package private methods used by BigDecimal code to add a BigInteger
     * with a long. Assumes val is not equal to INFLATED.
     */
    BigInteger add(long val) {
        if (val == 0)
            return this;
        if (signum == 0)
            return valueOf(val);
        if (Long.signum(val) == signum)
            return new BigInteger(add(mag, Math.abs(val)), signum);
        int cmp = compareMagnitude(val);
        if (cmp == 0)
            return ZERO;
        int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));
        resultMag = trustedStripLeadingZeroInts(resultMag);
        return new BigInteger(resultMag, cmp == signum ? 1 : -1);
    }

顺便说一句,我们都知道编译器使用valueOf()方法将原始值转换为Object(Unboxing)。并且Java自动将对象转换为原始对象.longValue()(Autoboxing)。

    BigInteger iObject = BigInteger.valueOf(2L);
    long iPrimitive = iObject.longValue();

我确信你已经知道如何在这种情况下使用BigInteger add方法来获取长值。

    BigInteger b = new BigInteger("2000");
    b.add(BigInteger.valueOf(2L));

答案 2 :(得分:0)

您也可以使用此版本(效率更高):

<强>的System.out.println(a.add(BigInteger.valueOf(2));

无需添加&#34;&#34;打印时,因为该值会自动转换为字符串,然后打印。