-5

I tried to validate digit and make this function.

public int digitCheck(String string)
    {
        int flag=0;

        for(int i=0;i<string.length();i++)
        {
            if(!Character.isDigit(string.charAt(i)))    
                flag++; 
        }       
        return flag;
    }

But it's always said an error on length on for

for(int i=0;i<string.length();i++)

Does anyone know why there's an error on length?

greenthunder
  • 697
  • 8
  • 19
  • 34
  • 1
    I assume you mean exception? What is the exception? is the string being passed in null, since that's the only error I can imagine happening calling `string.length()`? – Krease Dec 11 '13 at 04:23

2 Answers2

3

You forgot to check for null, and I think you want a boolean function like this.

public static boolean digitCheck(String string) {
  if (string != null) { // <--- Add This
    for (int i = 0; i < string.length(); i++) {
      if (!Character.isDigit(string.charAt(i)))
        return false;
    }
    return true; // we only got here if there were characters, and they're all digit(s).
  }
  return false; 
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Checking for null and using Java's Pattern class is another solution.

Here is a code sample:

public static final Pattern DIGIT_PATTERN = java.util.regex.Pattern.compile("[0-9]*");

public boolean digitCheck(String str) {
    if ( str == null ) {
        return true; // Assume Null is valid digit string;
    }
    return DIGIT_PATTERN.matcher(str).matches();
}
Krease
  • 15,805
  • 8
  • 54
  • 86
LHA
  • 9,398
  • 8
  • 46
  • 85