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?
How to handle NumberFormatException. Use try and catch block surrounding the code that can cause NumberFormatException. ) Another way of handling the exception is the use of throws keyword.
Since the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. It can be handled in code using a try-catch block.
It is a subclass of IllegalArgumentException class. To handle this exception, try–catch block can be used. While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt().
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
Java interprets numbers like 123f
as referring to a float
and 123d
as a double
, whereas plain 123
means an int
.
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