Java 如何验证电话号码
我正在尝试用java验证电话号码。在我的国家,电话号码要么以9开头,要么以8开头,只有8个号码。我已经做了Java 如何验证电话号码,java,Java,我正在尝试用java验证电话号码。在我的国家,电话号码要么以9开头,要么以8开头,只有8个号码。我已经做了 try { Integer.parseInt(phoneNo); } catch (NumberFormatException e) { msg += "Plese enter amount in Integers.\n"; } if (phoneNo.length() == 0) msg += "Please Enter Phone Number.\n"; if (
try {
Integer.parseInt(phoneNo);
}
catch (NumberFormatException e) {
msg += "Plese enter amount in Integers.\n";
}
if (phoneNo.length() == 0)
msg += "Please Enter Phone Number.\n";
if (phoneNo.length() != 8)
msg += "Invalid Phone Number.\n";
但是,当数字的第一位不是9或8时,我需要进行验证。我不完全确定我该怎么做。请解释您的代码是如何工作的,因为我是一名学生,我正在努力学习。您可以检查
电话号码的第一个字符。
:
if (phoneNo.charAt(0) != '9' && phoneNo.charAt(0) != '8') {
// the first character is not a 9 or an 8
}
来自Oracle的文档。字符串类和字符类中提供了将其组合在一起所需的方法 下面是一个示例程序,它实现了您所需的功能:
public class Foo {
public static void main(String[] args) {
// First try null and the empty string
System.out.println(isValidPhoneNumber(null));
System.out.println(isValidPhoneNumber(""));
// Now try an otherwise valid string that doesn't have the right first character
System.out.println(isValidPhoneNumber("01234567"));
// Now try an invalid string
System.out.println(isValidPhoneNumber("9a934581"));
// Finally a valid number
System.out.println(isValidPhoneNumber("94934581"));
}
static boolean isValidPhoneNumber(String phoneNo) {
// First validate that the phone number is not null and has a length of 8
if (null == phoneNo || phoneNo.length() != 8) {
return false;
}
// Next check the first character of the string to make sure it's an 8 or 9
if (phoneNo.charAt(0) != '8' && phoneNo.charAt(0) != '9') {
return false;
}
// Now verify that each character of the string is a digit
for (char c : phoneNo.toCharArray()) {
if (!Character.isDigit(c)) {
// One of the characters is not a digit (e.g. 0-9)
return false;
}
}
// At this point you know it is valid
return true;
}
}
它产生的输出是:
false
false
false
false
true
最后一个for-each循环可以通过使用带有显式计数器的for循环避免重新检查第一个字符,但是不检查单个int的性能增益并不超过for-each构造更干净的代码和更好的可读性
编辑:还请注意,我从原始问题中删除了验证错误消息,以提高可读性,因为OP要求解释代码的作用。将电话号码放入整数变量,而不是字符串变量。 然后使用stringVariable.charAt(0)检查第一个数字是否为9、8
对于电话号码的长度,使用int len=stringVariable.length() 以防您正在寻找正则表达式解决方案 您可以使用以下模式来执行检查 本质上,它所做的是
^
(?=(?:[8-9]){1}
(?=[0-9]{8})
*
输出: 有效电话号码
它发布了一个错误。说“表达式的类型必须是数组类型,但它已解析为字符串”,只需确保phoneNo不是null或空字符串即可。@mohanram,就此再问一个问题。在评论中回答是没有成效的。或者更好,用谷歌搜索。@ejp修正了逻辑。感谢您捕捉到这一点。您已从OP的代码中删除验证错误消息。你不认为这些很重要吗?@ErwinBolwidt我认为验证错误消息绝对重要!OP要求提供工作代码并解释它所做的事情,我只是试图保持它的简洁性以提高可读性。我将在答案中添加一个注释,说明您没有使用validPattern变量。难道你不应该删除这个声明吗?还有,投票支持使用正则表达式,我总是忘记;-)这也可以做到:
“^[89]\\d{7}$”
@P.J.Meisch-yep实际上更好。
public static void main(String[] args) {
String telephoneNr = "88765432";
if (telephoneNr.matches("^(?=(?:[8-9]){1})(?=[0-9]{8}).*")) {
System.out.println("Valid phone number!");
}
else {
System.out.println("Invalid!");
}
}