blakkheartt12 blakkheartt12 - 2 months ago 6
Java Question

I'm trying to test a string in java to see if it contains a digit

Hi can someone give some guidance. I'm trying to test a string to see if it has a digit and set a variable to true or false depending on the out come. This is what I have so far:

public static void main (String [] args) {
boolean hasDigit = false;
String passCode = "abc";
int valid = 0;

if (Character.isdigit(passCode)) {
hasDigit = true;
} else {
hasDigit = false;
}


Any help will be appreciated.

Thanks.

Answer

Loop through your string and test each character individually. Break the loop once you find a digit character:

boolean hasDigit = false;
String passCode = "abc";
for (int i = 0; i < passCode.length(); i++) {
    if(Character.isDigit(passCode.charAt(i))) {
        hasDigit = true;
        break;
    }
}