*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NumberFormatException" Watch "NumberFormatException" New topic
Author

NumberFormatException

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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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]
 
wood burning stoves
 
subject: NumberFormatException
 
Similar Threads
making a class visible
how to do big table pagination reading from database with jtable?
JTextField on getText() method
Socket not connected when using host ip address.
Errors when I get to run()