The challenge
Write a function that accepts a string, and returns true if it is in the form of a phone number.
Assume that any integer from 0-9 in any of the spots will produce a valid phone number.
Only worry about the following format:
(123) 456-7890 (don’t forget the space after the close parentheses)
Examples:
"(123) 456-7890" => true
"(1111)555 2345" => false
"(098) 123 4567" => false
The solution in Java code
Option 1:
public class Solution {
public static boolean validPhoneNumber(String phoneNumber) {
return phoneNumber.matches("\\(\\d{3}\\) \\d{3}-\\d{4}");
}
}
Option 2:
public class Solution {
public static boolean validPhoneNumber(String phoneNumber) {
char[] cStr = phoneNumber.toCharArray();
if(cStr[0] != '(') return false;
if(cStr[4] != ')') return false;
if(cStr[5] != ' ') return false;
if(cStr[9] != '-') return false;
for(int i = 1; i < cStr.length; i++){
if(i != 4 && i != 5 && i != 9){
if(!Character.isDigit(cStr[i])) return false;
}
}
return true;
}
}
Option 3:
public class Solution {
public static boolean validPhoneNumber(String phoneNumber) {
return phoneNumber.equalsIgnoreCase("(123) 456-7890");
}
}
Test cases to validate our solution
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PhoneExampleTests {
@Test
public void tests() {
assertEquals(true, Solution.validPhoneNumber("(123) 456-7890"));
assertEquals(false, Solution.validPhoneNumber("(1111)555 2345"));
assertEquals(false, Solution.validPhoneNumber("(098) 123 4567"));
}
}
Additional test cases
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PhoneTests {
@Test
public void basicTests() {
String msg = "Follow the formatting instructions carefully";
assertEquals(msg, true, Solution.validPhoneNumber("(123) 456-7890"));
assertEquals(msg, false, Solution.validPhoneNumber("(1111)555 2345"));
assertEquals(msg, false, Solution.validPhoneNumber("(098) 123 4567"));
assertEquals(msg, false, Solution.validPhoneNumber("(123)456-7890"));
}
@Test
public void formCharTests() {
String msg = "Pay attention to the formatting of the string and surrounding characters";
assertEquals(msg, false, Solution.validPhoneNumber("abc(123)456-7890"));
assertEquals(msg, false, Solution.validPhoneNumber("(123)456-7890abc"));
assertEquals(msg, false, Solution.validPhoneNumber("abc(123)456-7890abc"));
}
@Test
public void charTests() {
String msg = "Be careful with characters surrounding the phone number";
assertEquals(msg, false, Solution.validPhoneNumber("abc(123) 456-7890"));
assertEquals(msg, false, Solution.validPhoneNumber("(123) 456-7890abc"));
assertEquals(msg, false, Solution.validPhoneNumber("abc(123) 456-7890abc"));
}
@Test
public void badCharTests() {
String msg = "Be careful with non-digit characters inside phone number";
assertEquals(msg, false, Solution.validPhoneNumber("(123) 456-78f0"));
assertEquals(msg, false, Solution.validPhoneNumber("(123) 4e6-7890"));
assertEquals(msg, false, Solution.validPhoneNumber("(*23) 456-7890"));
}
}