简体   繁体   中英

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

How can I add any numbers to a BigInteger ? I am getting this error in eclipse:-

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));
    }
}

You cannot add normal integer to BigInteger .

But you can add one BigInteger to another BigInteger . So you should convert primitive integer to BigInteger as follows:

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

If you look at the source code of BigInteger, you will see an overload method for adding long number value. But they also mentioned it in method description that the method is private. That's why you could not be able to call it from your class.

/**
     * 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);
    }

Btw, as we all know the compiler uses valueOf() method to convert primitive value to Object (Unboxing). And Java automatic convert object to primitive object.longValue() (Autoboxing).

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

I am sure that you already knew how to use it with BigInteger add method in this case for long value.

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

You can also use this version(it is more efficient):

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

And no need to add "" when printing, as the value will be automatically converted into string, and then printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM