Exception to Number Format Exception with "D" and "F"?
Asked Answered
C

3

12

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?

Calisaya answered 10/3, 2014 at 19:53 Comment(1)
This is all explained here, in the doc: docs.oracle.com/javase/7/docs/api/java/lang/…Crepitate
S
15

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 is 12.3 as a double
  • 12.3f is 12.3 as a float
Seedman answered 10/3, 2014 at 19:56 Comment(2)
and to avoid this you better use a DecimalFormat to parse() your input - docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.htmlPrincessprinceton
Oh, ok, that explains that. Thank you for clearing that up. How interesting.Calisaya
A
6

Java interprets numbers like 123f as referring to a float and 123d as a double, whereas plain 123 means an int.

Aerophone answered 10/3, 2014 at 19:57 Comment(0)
P
5

Read the documentation on the number format supported by parseDouble. The f and d are instances of FloatTypeSuffix.

Peyter answered 10/3, 2014 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.