Search code examples
javaswingnetbeansjtextfield

Allow a jTextField to be blank?


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: 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;
    }