java BigInteger(long) 在 BigInteger 中有私有访问权限
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26104221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BigInteger(long) has private access in BigInteger
提问by Sunil Kumar
I am trying to store a big calculation in a BigInteger instance. I tried this :
我正在尝试在 BigInteger 实例中存储一个大计算。我试过这个:
BigInteger answer=new BigInteger(2+3);
and got the following error :
并得到以下错误:
temp.java:17: error: BigInteger(long) has private access in BigInteger
BigInteger answer=new BigInteger(2+3);
^
1 error
I know that instead of "2+3" there should be a string value. But i don't know how to satisfy that condition(assuming that i don't how much 2+3 is). Please tell me how to assign a calculated value to BigInteger object(assign 2+3 to BigInteger answer).
我知道应该有一个字符串值而不是“2+3”。但我不知道如何满足这个条件(假设我不知道 2+3 是多少)。请告诉我如何将计算值分配给 BigInteger 对象(将 2+3 分配给 BigInteger 答案)。
回答by Jon Skeet
If you want to perform the arithmetic using BigInteger
, you should create a BigInteger
for each value and then use BigInteger.add
. However, you don'tneed to use strings to do that. You may want to if your input is already a string and it might be long, but if you've already got a long
, you can use BigInteger.valueOf
. For example:
如果要使用 执行算术BigInteger
,则应BigInteger
为每个值创建一个,然后使用BigInteger.add
. 但是,你不要需要使用字符串来做到这一点。如果您的输入已经是一个字符串并且它可能很长,您可能想要,但是如果您已经有一个long
,则可以使用BigInteger.valueOf
. 例如:
BigInteger answer = BigInteger.valueOf(2).add(BigInteger.valueOf(3));
I certainly wouldn't convert a long
into a String
just to then pass it into the BigInteger
constructor.
我当然不会将 a 转换long
为 aString
然后将其传递给BigInteger
构造函数。
回答by Hovercraft Full Of Eels
You could just use BigInteger's add(...)
method:
你可以只使用 BigInteger 的add(...)
方法:
BigInteger answer = new BigInteger("2").add(new BigInteger("3"));
No worries about overflow with this solution.
无需担心此解决方案会溢出。