Muhammad Maqsoodur Rehman
Muhammad Maqsoodur Rehman

Reputation: 34257

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);

            }

    }

Upvotes: 1

Views: 2446

Answers (4)

vodkhang
vodkhang

Reputation: 18741

You can checkout the Pattern class in Java, really easy to work with regular expression using this class: https://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html.

Upvotes: 0

Binil Thomas
Binil Thomas

Reputation: 13779

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.

Upvotes: 1

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

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 (e.g. 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.

Upvotes: 1

Uri
Uri

Reputation: 89749

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.

Upvotes: 3

Related Questions