java phone number validation

后端 未结 4 1896
無奈伤痛
無奈伤痛 2021-01-18 08:13

Here is my problem:

Create a constructor for a telephone number given a string in the form xxx-xxx-xxxx or xxx-xxxx for a local number. Throw an exception if the for

4条回答
  •  生来不讨喜
    2021-01-18 08:51

    You could match those patterns pretty easily as suggested by BalusC.

    As a side note, StringTokenizer has been deprecated. From JavaDoc:

    StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

    An easier way to split your string into the appropriate segments would be:

    String phoneParts[] = phoneNumber.split("-");
    

提交回复
热议问题