File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Integer.parseInt : NumberFormatException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Integer.parseInt : NumberFormatException" Watch "Integer.parseInt : NumberFormatException" New topic

Integer.parseInt : NumberFormatException

Clive van Hilten

Joined: Feb 13, 2002
Posts: 18
Please would someone tell me why the following Integer.parseInt statement throws a NumberFormatException:
String string = properties.getProperty("flag");
int i = Integer.parseInt(string);
The value of string is "0" ("zero"). The error also occurs if string is "1".
[ March 12, 2003: Message edited by: Clive van Hilten ]
Chris Shepherd
Ranch Hand

Joined: Jun 27, 2000
Posts: 286
hmm only things I can think of is to check the length and make sure you don't have any extra spaces in there. ALso, try printing it out to your console right before you try to parse it to be sure it really is the value you expect.
My guess is that your string isn't what you think it is. You could test the parsing function by putting a known string value("0" or "1") directly into the parse method to prove that it works. It will, I'm sure, but just to test all points of failure...
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
This works as expected:

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

Catch the exception and print it out. That will give a clue as to what is happening.

Please ignore post, I have no idea what I am talking about.
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

jantar mantar

Joined: Mar 12, 2003
Posts: 5
as chris mentioned earlier, most of the time, the problem is with the blank spaces.
Try using :
The trim function of the string class will chop of any spaces in ur string.
Hope this helps.
Clive van Hilten

Joined: Feb 13, 2002
Posts: 18
Thanks very much for all the replies - the problem turned out to be a blank space - the trim() method sorted it out!
[ March 13, 2003: Message edited by: Clive van Hilten ]
I agree. Here's the link:
subject: Integer.parseInt : NumberFormatException
It's not a secret anymore!