I have run into a very strange problem in my code. I have a simple temperature converter where the user enters the temperature in Celsius and, after pressing "Convert", the temperature in Fahrenheit is shown. If the user does not enter something valid (anything that is not a number or decimal) an error dialog box is shown. Code:
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String tempFahr = (String) enterDegreesC.getText();
double tempF = Double.valueOf(tempFahr);
double tempFConverted = tempF * 1.8 +32;
displayDegreesF.setText(tempFConverted + " Farenheit");
}
catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(frmTemperatureConverter, "Please Enter a Number.", "Conversion Error", JOptionPane.ERROR_MESSAGE);
}
}
});
Pretty straight forward and simple code and works well except for one thing. When I enter a combination of a number followed by the letters "f" or "d", no error dialog is shown and the temperature in Fahrenheit is calculated using the digit in front on the letter. This ONLY happens with "d" and "f" (and "D" and "F") and not any other letter. I am stumped on this one. Why would only these two letters when placed after a digit cause the exceptions not to be thrown and a calculation to proceed?
some languages allow you to put letters after number literals to signify what type it is.
if you simply wrote
12.3
, it might not know whether it is a float or a double(or it'd have to infer or cast it).Your number parser must be picking up on these letters.
12.3d
is12.3
as adouble
12.3f
is12.3
as afloat
Java interprets numbers like
123f
as referring to afloat
and123d
as adouble
, whereas plain123
means anint
.Read the documentation on the number format supported by
parseDouble
. Thef
andd
are instances of FloatTypeSuffix.