简体   繁体   中英

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

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() . 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. 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; so it will definitely not match the next valid char and hence you break out of the loop with a true flag. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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