2017-01-16 59 views
-1

我试图编写一个Java计算器。试图计算以下时,正在到一些NumberFormat的例外:当两个整数相乘时NumberFormatException

99.9(4x/8+k) 

有趣的是,它给我的错误,我分发99.9后只有99.9和产品“k”是大于或等于1000.因此,对于大于10的值。在我的代码中,我尝试使用方程的所有常量的和来加载字符串变量,然后发生错误。 下面的代码是什么样子:

double constantSum = 0; 
//create a stringtokenizer object and convert each token to a double as 
//follows, then, add the double to constantSum 
constantSum = constantSum + Double.valueOf(token);//the token comes 
//from the stringtokenizer object 

是Double.valueOf(标记)接收输入1098.900这是 的99.9和11的产品,注意输入已经被四舍五入到千分之 地方我在代码中初始化的一个NumberFormat对象。

如何摆脱这种NumberFormat的例外

这里的任何想法是例外的样子细节:对于输入字符串:线程“main” java.lang.NumberFormatException 例外“1,098.900 “ 在sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) 在sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)

感谢

+0

你错了,输入不是'1098.900',它是'1,098.900'。看到错误信息。为什么你甚至会把你的代码中的中间值作为字符串? – Andreas

+0

[什么是NumberFormatException,我该如何解决它?]可能的重复(http://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it) – xenteros

回答

2

这位前ception可能是由token字符串中的逗号引起的。对于一个快速修复,你可以尝试去除所有的逗号:

constantSum += Double.valueOf(token.replaceAll(",", "")); 
               ^^^^ this removes all commas 
0

你不能在你想要变成双精度的字符串中有逗号。删除逗号,它应该工作。