The problem I'm having is when I check to see if the string contains any characters it only looks at the first character, not the whole string. For instance, I would like to be able to input "123abc" and the characters are recognized so it fails. I also need the string to be 11 characters long and since my program only works with 1 character it cannot go any further.
Here is my code so far:
public static int phoneNumber(int a)
{
while (invalidinput)
{
phoneNumber[a] = myScanner.nextLine();
if (phoneNumber[a].matches("[0-9+]") && phoneNumber[a].length() == 11 )
{
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
For instance why if I take away the checking to see the phoneNumber.length()
, it still only registers 1 character; so, if I enter "12345", it still fails. I can only enter "1" for the program to continue.
If someone could explain how this works to me that would be great.
Your regex
and if condition
is wrong. Use it like this:
if ( phoneNumber[a].matches("^[0-9]{11}$") ) {
System.out.println("Continue");
invalidinput = false;
}
This will allow only phoneNumber[a]
to be a 11 characters long comprising only digits 0-9
.