I need to generate random values and print them.
But it throws an Exception:
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)
It happens only here:
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));
}
And precision is constant:
private static final DecimalFormat PRECISION = new DecimalFormat("#.#");
But all looks ok.
How to solve this issue?
The input string contains ,
instead of .
. Replace the ,
with .
to get rid of the exception. Ideally, the input should be 35.9
and not 35,9
.
If you are using ,
as the decimal separator, then you could use the DecimalFormatSymbols
to replace ,
as the decimal separator.
The following code demonstrates the use of DecimalFormatSymbols
class:
DecimalFormat df = new DecimalFormat("#.#");
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);
System.out.println(df.parse("35,9"));
The above code prints 35.9