我遇到的问题是检查字符串是否包含任何仅查看第一个字符而不是整个字符串的字符。例如,我希望能够输入“ 123ABC”,并且字符已识别,以使其失败。我还需要该字符串长11个字符,并且由于我的程序仅适用于1个字符,因此无法进一步发展。 到目前为止,我的代码是我的代码:
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;
}
例如,如果我拿走检查查看
phoneNumber.length()
,它仍然只登记1个字符;因此,如果我输入“ 12345”,它仍然会失败。我只能输入“ 1”,以便该程序继续。
如果有人可以解释这对我来说是很棒的。您的
regex
if ( phoneNumber[a].matches("^[0-9]{11}$") ) {
System.out.println("Continue");
invalidinput = false;
}
这只会允许
phoneNumber[a]
是一个11个字符,其中包含数字0-9
+应该在集合之外,或者您可以特异性尝试匹配这样的11位数字: ^ [0-9] {11} $( ^和$锚定在字符串的开始和结尾)。您需要将“+”放在“]”之后。因此,您将其更改为:
phoneNumber[a].matches("[0-9]+")
public static int phoneNumber(int a)
{
while (invalidinput)
{
int x = 0;
for(int i = 0; i < phoneNumber[a].length(); i++)
{
char c = phoneNumber[a].charAt(i);
if(c.matches("[0-9+]")){
x++;
}
}
if (x == phoneNumber[a].length){
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
0
9
+
? 如果是这样,那么您应该使用正则表达式