简体   繁体   English

关于java.math.BigInteger

[英]Regarding java.math.BigInteger

The problem im facing with BigInteger when i try computing a string like "7+3" and then storing the result in a BigInteger variable, it throws a NumberFormat exception. 当我尝试计算“ 7 + 3”之类的字符串然后将结果存储在BigInteger变量中时,BigInteger面临的问题是,它引发NumberFormat异常。 Any pointers on how this can worked on? 关于如何工作的任何指示? Eg: 例如:

    String ist="7+2";
    java.math.BigInteger a = new java.math.BigInteger(ist);

BigInteger sum = (new BigInteger(7)).add(new BigInteger(3)) BigInteger sum =(new BigInteger(7))。add(new BigInteger(3))

JepLite , Jeks , JbcParser , MESP , and JEP are all libraries can parse expressions like "7+3" JepLiteJeksJbcParserMESPJEP都可以解析“ 7 + 3”之类的表达式

BigInteger cannot evaluate expressions. BigInteger无法评估表达式。 In fact, I don't know of any solution in Java to do evaluation of arbitrary arithmetic expressions - you could try Groovy instead or parse the expression yourself. 实际上,我不知道Java中有任何解决方案可以对任意算术表达式进行评估-您可以尝试使用Groovy或自己解析该表达式。

If you're considering parsing, the simplest way is probably to convert from infix notation to polish notation and then evaluate the polish form one operator at a time. 如果您正在考虑分析,最简单的方法可能是从中缀表示法转换为修饰符,然后一次由一个运算符评估修饰符。 Look up the shunting yard algorithm. 查找调车场算法。

BigInteger will only understand that, when you pass a numeric value like new java.math.BigInteger("9") . 当您传递数字值(例如new java.math.BigInteger("9")时, BigInteger只会理解这一点。 It can not parse what you provide. 它无法解析您提供的内容。

As diciu and Peter Lang have stated, BigInteger cannot evaluate expressions. 正如diciu和Peter Lang所说,BigInteger无法评估表达式。 If you need numbers that, when evaluated, would overflow some primitive like an Integer, you can create two BigIntegers and then evaluate the result. 如果您需要的数字在求值时会溢出某些原语(例如整数),则可以创建两个BigInteger,然后评估结果。 For instance: 例如:

java.math.BigInteger a = new java.math.BigInteger("7").add(new java.math.BigInteger("2"));

If you really want to evaluate strings and you don't mind using s-expressions then you could use Clojure: 如果您真的想评估字符串,并且不介意使用s表达式,则可以使用Clojure:

Clojure 1.0.0-
user=> (def s "(+ 7 3)")
#'user/s
user=> (load-string s)
10
user=>

Here are instructions for invoking Clojure from Java 这是从Java调用Clojure的说明

If you take this route be careful to sanitize the strings before you evaluate them or you could leave yourself open to injection attacks. 如果您采用这种方法,请在评估字符串之前仔细清理字符串,否则您可能会遭受注入式攻击。

BTW when Clojure evaluates the expression it will use a BigInteger if needed, for instance: 顺便说一句,当Clojure计算表达式时,如果需要,它将使用BigInteger,例如:

user=> (def s "(+ 1 2)")
#'user/s
user=> (def r (load-string s))
#'user/r
user=> (. r getClass)
java.lang.Integer
user=> (def s "(+ 1000000000000000000000000 20000000000000000000000)")
#'user/s
user=> (def r (load-string s))
#'user/r
user=> (. r getClass)
java.math.BigInteger
user=>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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