简体   繁体   English

如何在 Java 中验证电话号码(美国格式)?

[英]How to validate phone number(US format) in Java?

I just want to know where am i wrong here:我只想知道我错在哪里:

import java.io.*;


    class Tokens{   
            public static void main(String[] args)
            {
               //String[] result = "this is a test".split("");

                String[] result = "4543 6546 6556".split("");
                boolean flag= true;         

                String num[] = {"0","1","2","3","4","5","6","7","8","9"};
                String specialChars[] = {"-","@","#","*"," "};


                for (int x=1; x<result.length; x++)
                {   
                    for (int y=0; y<num.length; y++)
                    {
                        if ((result[x].equals(num[y])))
                        {
                            flag = false;
                            continue;

                        }
                        else
                        {
                            flag = true;
                        }


                        if (flag == true)
                        break;

                    }   

                if (flag == false)
                break;

                }           

                System.out.println(flag);

            }

    }

If this is not homework, is there a reason you're avoiding regular expressions?如果这不是家庭作业,您是否有理由避免使用正则表达式?

Here are some useful ones: http://regexlib.com/DisplayPatterns.aspx?cattabindex=6&categoryId=7这里有一些有用的: http : //regexlib.com/DisplayPatterns.aspx? cattabindex=6& categoryId=7

More generally, your code doesn't seem to validate that you have a phone number, it seems to merely validate that your strings consists only of digits.更一般地说,您的代码似乎并没有验证您是否拥有电话号码,它似乎只是验证了您的字符串是否仅由数字组成。 You're also not allowing any special characters right now.您现在也不允许使用任何特殊字符。

Asides from the regex suggestion (which is a good one), it would seem to make more sense to deal with arrays of characters rather than single-char Strings.除了正则表达式的建议(这是一个很好的建议)之外,处理字符数组而不是单字符字符串似乎更有意义。

In particular, the split("") call (shudder) could/should be replaced by toCharArray() .特别是, split("")调用(不寒而栗)可以/应该被toCharArray()替换。 This lets you iterate over each individual character, which more clearly indicates your intent, is less prone to bugs as you know you're treating each character at once, and is more efficient*.这让您可以迭代每个单独的字符,这更清楚地表明您的意图,并且由于您知道正在一次处理每个字符,因此更不容易出错,并且效率更高*。 Likewise your valid character sets should also be characters.同样,您的有效字符集也应该是字符。

Your logic is pretty strangely expressed;你的逻辑表达得很奇怪; you're not even referencing the specialChars set at all, and the looping logic once you've found a match seems odd.您甚至根本没有引用 specialChars 集,一旦找到匹配项,循环逻辑似乎很奇怪。 I think this is your bug;我认为这是你的错误; the matching seems to be the wrong way round in that if the character matches the first valid char, you set flag to false and continue round the current loop;匹配似乎是错误的方式,因为如果字符匹配第一个有效字符,则将标志设置为false并继续当前循环; so it will definitely not match the next valid char and hence you break out of the loop with a true flag.所以它肯定不会匹配下一个有效字符,因此你用一个true标志跳出循环。 Always.总是。

I would have thought something like this would be more intuitive:我本以为这样的事情会更直观:

private static final Set<Character> VALID_CHARS = ...;

public boolean isValidPhoneNumber(String number)
{
    for (char c : number,toCharArray())
    {
        if (!VALID_CHARS.contains(c))
        {
           return false;
        }
    }

    // All characters were valid
    return true;
}

This doesn't take sequences into account (eg the strings "--------** " and "1" would be valid because all individual characters are valid) but then neither does your original code.这不考虑序列(例如,字符串“--------**”和“1”将是有效的,因为所有单个字符都是有效的),但您的原始代码也不考虑。 A regex is better because it lets you specify the pattern, I supply the above snippet as an example of a clearer way of iterating through the characters.正则表达式更好,因为它可以让您指定模式,我提供上面的代码片段作为一个更清晰的字符迭代方式的示例。

*Yes, premature optimization is the root of all evil, but when better , cleaner code also happens to be faster that's an extra win for free. *是的,过早的优化是万恶之源,但更好更干净的代码也恰好更快,这是免费的额外胜利。

Maybe this is overkill, but with a grammar similar to:也许这有点矫枉过正,但语法类似于:

<phone_numer> := <area_code><space>*<local_code><space>*<number> |
                 <area_code><space>*"-"<space>*<local_code><space>*"-"<space>*<number>
<area_code>   := <digit><digit><digit> | 
                 "("<digit><digit><digit>")"
<local_code>  := <digit><digit><digit>
<number>      := <digit><digit><digit><digit>

you can write a recursive descent parser.你可以写一个递归下降解析器。 See this page for an example.有关示例,请参阅此页面

您可以在 Java 中签出 Pattern 类,使用此类非常容易使用正则表达式: https : //docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM