Java check phone number

By | 17/11/2014

Program asks for a phone number and checks if it is valid.

CheckPhoneNo.java:

import java.util.Scanner;

public class CheckPhoneNo {
 boolean go=true;
 private void run() {
  Scanner reader=new Scanner(System.in);
  String phoneNo;

  while(go) {
   System.out.println("Enter a phone number (6-15 numbers, may include an area code and spaces)");
   phoneNo = reader.nextLine();
   String phoneNoWithoutSpaces=removeSpaces(phoneNo);
   checkPhoneNo(phoneNoWithoutSpaces);
  }
  reader.close();
 }
 private String removeSpaces(String input) {
  input=input.replaceAll(" ", "");
  return input;
 }
 private void checkPhoneNo(String input) {
  //\\+? "+" allowed but not required  \\d digit. {6,15} between 6 and 15 characters (digits in this case)
  if(input.matches("\\+?\\d{6,15}")) {
   System.out.println("Phone number "+input+" is ok!");
   go=false;
  }
  else {
   System.out.println("Phone number "+input+" has errors.");
  }
 }
 public static void main(String[] args) {
  CheckPhoneNo program = new CheckPhoneNo();
  program.run();
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *