This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes NumberFormatException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NumberFormatException" Watch "NumberFormatException" New topic


Candy Bortniker
Ranch Hand

Joined: Mar 17, 2003
Posts: 123
I am getting this exception when my textfield is empty. What can I do to fix the problem? I start out with numbers in getText() but when I remove the last one I get the exception. This is the code where the error is happening.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Any time you use Long.parseLong() or any similar method that turns a String into a number, you face the possibility that the String isn't a valid number. All such Java methods report this problem by throwing a NumberFormatException. You need to catch the exception and do one of two things: report the error to the user (if they typed in invalid input) or substitute a default value (if you want non-numbers to be equal to 0, for example.) The latter strategy would look like

By the way, I can't help but remark that having a variable of type "long" named "text" makes my head hurt. Well-chosen variable names go a long way towards making code easier to write and to read.
Now, what is going on with the following line of code?

You've parsed a String to create a long, and now you're turning the long into a String and then parsing it as an int -- why? Why not simply

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: NumberFormatException
It's not a secret anymore!