我需要生成随机值并打印它们。
但它引发了一个异常:
java.lang.NumberFormatException: For input string: "35,9"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at com.epam.lab.model.sweets.SweetsGenerator.paramFormatter(SweetsGenerator.java:71)
at com.epam.lab.model.sweets.SweetsGenerator.next(SweetsGenerator.java:55)
at com.epam.lab.model.NewYearGift.generate(NewYearGift.java:40)
at com.epam.lab.controller.GiftController.generateGift(GiftController.java:86)
at com.epam.lab.controller.GiftController.showGiftContent(GiftController.java:213)
at com.epam.lab.view.Application.process(Application.java:89)
at com.epam.lab.view.Application.estimateUserInput(Application.java:49)
at com.epam.lab.view.Application.start(Application.java:43)
at com.epam.lab.view.Main.main(Main.java:19)
只在这里发生:
public Sweets next() {
Sweets current = instances[rand.nextInt(instances.length)];
double sugarParam = paramFormatter(randomSugarLevel(), PRECISION);
double weightParam = paramFormatter(randomWeight(), PRECISION);
try {
return (Sweets) current.getClass()
.getConstructor(double.class, double.class)
.newInstance(sugarParam, weightParam);
// Report programmer errors at run time:
} catch (Exception e) {
LOG.error("RuntimeException", e);
throw new RuntimeException(e);
}
}
private double paramFormatter(double sugarParam, DecimalFormat df) {
return Double.parseDouble(df.format(sugarParam));
}
private double randomWeight() {
return WEIGHT_MIN + (Math.random() * ((WEIGHT_MAX - WEIGHT_MIN) + 1));
}
private double randomSugarLevel() {
return SUGAR_MIN + (Math.random() * ((SUGAR_MAX - SUGAR_MIN) + 1));
}
精确度是恒定的:
private static final DecimalFormat PRECISION = new DecimalFormat(“#。#”);
但一切看起来还不错。
如何解决这个问题?
答案 0 :(得分:5)
输入字符串包含,
而不是.
。将,
替换为.
以删除异常。理想情况下,输入应为35.9
而不是35,9
。
如果您使用,
作为小数点分隔符,则可以使用DecimalFormatSymbols
将,
替换为小数点分隔符。
以下代码演示了DecimalFormatSymbols
class:
DecimalFormat df = new DecimalFormat("#.#");
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);
System.out.println(df.parse("35,9"));
以上代码打印35.9