关于 java.math.BigInteger
当我尝试计算像“7+3”这样的字符串,然后将结果存储在 BigInteger 变量中时,我面临 BigInteger 的问题,它会引发 NumberFormat 异常。关于如何进行此操作有任何指示吗? 例如:
String ist="7+2";
java.math.BigInteger a = new java.math.BigInteger(ist);
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. Any pointers on how this can worked on?
Eg:
String ist="7+2";
java.math.BigInteger a = new java.math.BigInteger(ist);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
BigInteger sum = (new BigInteger(7)).add(new BigInteger(3))
JepLite, Jeks,JbcParser、MESP 和 JEP 都是可以解析“7+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"
BigInteger 无法计算表达式。
事实上,我不知道 Java 中有任何解决方案可以对任意算术表达式进行求值 - 您可以尝试使用 Groovy 或自己解析表达式。
如果您正在考虑解析,最简单的方法可能是从中缀表示法转换为修饰表示法,然后一次评估一个运算符的修饰形式。查看调车场算法。
BigInteger cannot evaluate expressions.
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.
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
仅当您传递像new java.math.BigInteger("9")
这样的数值时才会理解这一点。它无法解析您提供的内容。BigInteger
will only understand that, when you pass a numeric value likenew java.math.BigInteger("9")
. It can not parse what you provide.正如 diciu 和 Peter Lang 所说,BigInteger 无法计算表达式。如果您需要在计算时会溢出某些基元(例如 Integer)的数字,则可以创建两个 BigInteger,然后计算结果。例如:
As diciu and Peter Lang have stated, BigInteger cannot evaluate expressions. If you need numbers that, when evaluated, would overflow some primitive like an Integer, you can create two BigIntegers and then evaluate the result. For instance:
如果你真的想计算字符串并且不介意使用 s 表达式,那么你可以使用 Clojure:
这里有 从 Java 调用 Clojure 的说明
如果您采用此路线,请在评估字符串之前小心清理字符串,否则您可能会遭受注入攻击。
顺便说一句,当 Clojure 计算表达式时,如果需要,它将使用 BigInteger,例如:
If you really want to evaluate strings and you don't mind using s-expressions then you could use Clojure:
Here are instructions for invoking Clojure from Java
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: