error catching
Hi I am trying to resolve this problem catching a double, any help would be very appreciated I just cant figure it out.
If I put in a character it catches the error
if I put in 3h it catches the error
but if I put any number in with the letter "f" it doesnt catch it - any ideas here is my code
double unitPrice = 0.0;
boolean inValid = false;
do
{
String strUnitPrice = JOptionPane.showInputDialog ( (null,"Please enter unit price");
try
{
unitPrice = Double.parseDouble(strUnitPrice);
if(unitPrice <= 0.0)
inValid = true;
else
inValid = false;
System.out.println(unitPrice + " " + inValid);
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"You must enter a valid price");
inValid = true;
System.out.println(unitPrice + " " + inValid);
}
}
while(inValid);
[950 byte] By [
leah7a] at [2007-11-27 4:33:24]

If you read the api for the parseDouble method, it says it returns the same value that the valueOf() method would. If you scroll to the valueOf method, it describes what the correct syntax for a parseable double is. In java, a float literal can have an 'f' at the end, and a double literal can have a 'd'. So if the number has an f at the end, it will interpret that as a float literal, and the parse method will accept it. You can read more about literals here:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
Edit: If you don't want to allow the f or d for some reason, then manually check if the input ends with either of those, and reject the input if it does.
Message was edited by:
hunter9000
It is a simple issue, man.
as you know Java has two primitive data types can store decimal point number: float and double, but any decimal point literal is treated by default as double, I mean that when you declare for instance:
float var = 3.14
the compiler will refused because he wants an explicit cast like that:
float var = (float) 3.14
to enforce the compiler to treat decimal point literal as a float, you can append your literal value with the letter 'f' or 'F'.
That is why parsing process succeeded with the letter 'f ' in your parsed string, but bote that the letter 'f' must be the last letter in your literal, if you insert 'f' in your literal it will throw NumberFormatException
then your parsed float value will be implicitly casted to double before assigning to the double variable unitPrice
Thats all.
Ahmad Elsafty.