Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top