Mitch Stallings
Mitch Stallings

Reputation: 65

Trouble with string length

So I am attempting to get my program to run through each character in my string and if it finds a number, then to print the password and exit the for loop and the while loop (did not include the while loop but it is 'while (test == 0)'). But if I enter a password without a number, it will scan the entire string and print that I need a number. For some reason, when I enter a password with a number, it works perfectly. But when I enter a password without a number, I get an error message... Any ideas?

Here's my code:

for (int num = 0; num <= passw.length(); num++){
    if (Character.isDigit(passw.charAt(num))){
        num += 1000;
        test++;
        System.out.println(passw);
    }

    if (num >= passw.length() && num <= 1000){
        System.out.println("You need a number");
    }

}

Upvotes: 0

Views: 77

Answers (3)

Bohemian
Bohemian

Reputation: 425348

You are going about it the wrong way. Replace all your code with just this:

if (passw.matches("\\D*")) {
    System.out.println("You need a number");
}

This uses the regex \D*, which means "every character is a non-digit"

Upvotes: 2

awolfe91
awolfe91

Reputation: 1647

for (int num = 0; num <= passw.length(); num++){

will go to the character past the end of the string. Just do

for (int num = 0; num < passw.length(); num++){

Hope that helps!

Upvotes: 2

kosa
kosa

Reputation: 66667

for (int num = 0; num <= passw.length(); num++){

index starts from 0 not 1

so loop should be:

for (int num = 0; num < passw.length(); num++){

Upvotes: 2

Related Questions