Reputation: 65
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
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
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
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