Note that there are some explanatory texts on larger screens.

plurals
  1. POjava phone number validation
    primarykey
    data
    text
    <p>Here is my problem:</p> <p>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 format is not valid.</p> <p>So I was thinking to validate it using a regular expression, but I don't know if I'm doing it correctly. Also what kind of exception would I have to throw? Do I need to create my own exception?</p> <pre><code> public TelephoneNumber(String aString){ if(isPhoneNumberValid(aString)==true){ StringTokenizer tokens = new StringTokenizer("-"); if(tokens.countTokens()==3){ areaCode = Integer.parseInt(tokens.nextToken()); exchangeCode = Integer.parseInt(tokens.nextToken()); number = Integer.parseInt(tokens.nextToken()); } else if(tokens.countTokens()==2){ exchangeCode = Integer.parseInt(tokens.nextToken()); number = Integer.parseInt(tokens.nextToken()); } else{ //throw an excemption here } } } public static boolean isPhoneNumberValid(String phoneNumber){ boolean isValid = false; //Initialize reg ex for phone number. String expression = "(\\d{3})(\\[-])(\\d{4})$"; CharSequence inputStr = phoneNumber; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){ isValid = true; } return isValid; } </code></pre> <p>Hi sorry, yes this is homework. For this assignments the only valid format are xxx-xxx-xxxx and xxx-xxxx, all other formats (xxx)xxx-xxxx or xxxxxxxxxx are invalid in this case.</p> <p>I would like to know if my regular expression is correct</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload