Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NumberFormatException

 
Candy Bortniker
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic