Java-查看字符串中是否包含任何字符 [英] Java - See if a string contains any characters in it
问题描述
我遇到的问题是,当我检查字符串是否包含任何字符时,它只会查看第一个字符而不是整个字符串。例如,我希望能够输入 123abc,并且可以识别字符,因此失败。我还需要将字符串的长度设置为11个字符,并且由于我的程序只能使用1个字符,因此不能再进行任何操作了。
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;
}
例如为什么我不带支票去查看phoneNumber.length( )它仍然只注册1个字符,因此如果我输入 12345,它仍然会失败。我只能输入 1,程序才能继续。
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;
}
这将只允许 phoneNumber [a]
为11个字符,仅包含数字 0-9
This will only allow phoneNumber[a]
to be a 11 character long comprising only digits 0-9
这篇关于Java-查看字符串中是否包含任何字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!