Issue
I created a simple application where the user enters two values and automatically updates a textfield with the answer and checks to see if the input is numbers or not.
The code (used from this question: href="http://How%20to%20Auto%20Calculate%20input%20numeric%20values%20of%20Text%20Field%20in%20JAVA" rel="nofollow">How to Auto Calculate input numeric values of Text Field in JAVA) to check the user input is as follows:
private boolean isDigit(String string)
{
for (int n = 0; n < string.length(); n++)
{
//get a single character of the string
char c = string.charAt(n);
if (!Character.isDigit(c))
{
//if its an alphabetic character or white space
return false;
}
}
return true;
}
It works but when the textfields are blank, the following error message comes up: java.lang.NumberFormatException: For input string: ""
.
How can I alter the code I have used so that blank textfields are acceptable and do not produce errors?
Solution
You can just add an if
at start to check if the string is legal
private boolean isDigit(String string)
{
if(string == null || string.isEmpty()) {
return false;
}
for (int n = 0; n < string.length(); n++)
{
//get a single character of the string
char c = string.charAt(n);
if (!Character.isDigit(c))
{
//if its an alphabetic character or white space
return false;
}
}
return true;
}
Answered By - Ami Hollander
Answer Checked By - Senaida (JavaFixing Volunteer)