This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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.
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