This program makes temperature conversions using an itemListener
outputValue is a protected double
outputString is also protected
output is a is a JTextField
and output type is a protected char
public void itemStateChanged(ItemEvent e) {
inputValue = Double.parseDouble(textField.getText());
//the input value is converted to the outputValue based on the outputType
outputString = String.valueOf(outputValue); //set output value to string
outputString = String.format(" %0.2f", outputValue); //format to .00
output.setText( outputString + (char) 0x00B0 + outputType);}
When I run the program I get:
Exception in thread "AWT-EventQueue-0" java.util.MissingFormatWidthException: 0.2f,
with a long list of (unknown sources).
Use format string %.2f
:
String.format(" %.2f", outputValue);
The accepted answer from Glenn Lane answers the question, how to do this correctly.
As for why the exception occurred, a careful search of the Formatter javadoc reveals this about the 0
flag:
Requires the output to be padded with leading zeros to the minimum field width following any sign or radix indicator except when converting NaN or infinity. If the width is not provided, then a MissingFormatWidthException will be thrown.
So, %0.2f
is saying that the number should be padded with zeroes to n
places before the decimal (and 2 digits should be shown after the decimal). But n
is left unspecified.
That's why %0.2f
throws a MissingFormatWidthException
, and %.2f
doesn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With