Alphabetic Telephone Number Translator in Java

Sheeraz Gul Oct 12, 2023
  1. Alphabetic Telephone Number Translator in Java
  2. Use regex and the switch Statement to Generate an Alphabetic Telephone Number Translator
  3. Use Google Guava to Generate an Alphabetic Telephone Number Translator
Alphabetic Telephone Number Translator in Java

This tutorial demonstrates how to generate an alphabetic telephone number translator in Java.

Alphabetic Telephone Number Translator in Java

Sometimes the companies use the phone number format like 555-GET-FOOD, which is a standardized process of writing a phone number to make it easier to remember for the customer. The standard version of the letter to numbers for the phone numbers is:

A, B, and C = 2
D, E, and F = 3
G, H, and I = 4
J, K, and L = 5
M, N, and O = 6
P, Q, R, and S = 7
T, U, and V = 8
W, X, Y, and Z = 9

Based on the above scenario, we can create a phone number translator from alphabetic phone numbers to numbers. This can be achieved via different methods.

Use regex and the switch Statement to Generate an Alphabetic Telephone Number Translator

The Regex is a package in Java that is used to match the given pattern, so if the standard phone number format is 123-XXX-XXXX, the regex pattern for this number will be [0-9]{3}-[a-zA-Z]{3}-[a-zA-Z]{4}, which will be used to match the input phone number with the standard format.

The Switch statement can be used to generate cases where a number will be added to the phone number string based on letters and numbers provided in the above list. Let’s try to implement this example:

package delftstack;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
  public static void main(String[] args) {
    // user input for the phone number
    Scanner PhoneNumber_Input = new Scanner(System.in);

    System.out.println("Please enter a Phone number with the format: (123-XXX-XXXX) ");

    // Convert the phone number to a string
    String Phone_Number = PhoneNumber_Input.nextLine();
    if (Validate_PhoneNumber(Phone_Number)) {
      Phone_Number = Phone_Number.toUpperCase();
      String Translated_PhoneNumber = Translate_PhoneNumber(Phone_Number);
      System.out.println(Translated_PhoneNumber);
    } else {
      System.out.println("Wrong phone number format.");
      return;
    }
  }

  private static boolean Validate_PhoneNumber(String Phone_Number) {
    Pattern Number_Pattern = Pattern.compile("[0-9]{3}-[a-zA-Z]{3}-[a-zA-Z]{4}");

    // Create The matcher object.
    Matcher Number_Matcher = Number_Pattern.matcher(Phone_Number);
    if (Number_Matcher.find()) {
      return true;
    }
    return false;
  }

  public static String Translate_PhoneNumber(String Phone_Number) {
    String Phone_Number_Result = "123-";
    String Phone_Number_Suffix = Phone_Number.substring("123-".length());
    for (int i = 0; i < Phone_Number_Suffix.length(); i++) {
      char Number_Character = Phone_Number_Suffix.charAt(i);
      if (Character.isLetter(Number_Character)) {
        switch (Number_Character) {
          case 'A':
          case 'B':
          case 'C':
            Phone_Number_Result += "2";
            break;
          case 'D':
          case 'E':
          case 'F':
            Phone_Number_Result += "3";
            break;
          case 'G':
          case 'H':
          case 'I':
            Phone_Number_Result += "4";
            break;
          case 'J':
          case 'K':
          case 'L':
            Phone_Number_Result += "5";
            break;
          case 'M':
          case 'N':
          case 'O':
            Phone_Number_Result += "6";
            break;
          case 'P':
          case 'Q':
          case 'R':
          case 'S':
            Phone_Number_Result += "7";
            break;
          case 'T':
          case 'U':
          case 'V':
            Phone_Number_Result += "8";
            break;
          case 'W':
          case 'X':
          case 'Y':
          case 'Z':
            Phone_Number_Result += "9";
            break;
        }
      } else if (Number_Character == '-') {
        Phone_Number_Result += "-";
      }
    }
    return Phone_Number_Result;
  }
}

The code above contains three methods, the first is the main method, the second is the method to validate the phone number according to the regex method, and the third is to translate the phone number. See the output:

Please enter a Phone number with the format: (123-XXX-XXXX)
444-CAT-GOOD
123-228-4663

As we can see, the phone number 444-CAT-GOOD is translated to 123-228-4663.

Use Google Guava to Generate an Alphabetic Telephone Number Translator

Google Guava is a library for Java that provides a lot of operations. Guava includes ImmutableMultimap, which can be used to store the data according to the format described in the list above.

This ImmutableMultimap will then be used with the Splitter from the guava library with the Java 8 inline function syntax to generate a phone number from the input number with letters.

Make sure the Google Guava library is added to your environment. Let’s try to implement an example based on the above scenario:

package delftstack;

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Example {
  public static void main(String[] args) {
    ImmutableMultimap<String, String> Translate_PhoneNumber =
        new ImmutableMultimap.Builder<String, String>()
            .putAll("2", Lists.<String>newArrayList("A", "B", "C"))
            .putAll("3", Lists.<String>newArrayList("D", "E", "F"))
            .putAll("4", Lists.<String>newArrayList("G", "H", "I"))
            .putAll("5", Lists.<String>newArrayList("J", "K", "L"))
            .putAll("6", Lists.<String>newArrayList("M", "N", "O"))
            .putAll("7", Lists.<String>newArrayList("P", "Q", "R", "S"))
            .putAll("8", Lists.<String>newArrayList("T", "U", "V"))
            .putAll("9", Lists.<String>newArrayList("W", "X", "Y", "Z"))
            .build();
    // Get the user input
    Scanner Input_PhoneNumber = new Scanner(System.in);
    System.out.print("Enter a phone number with the format (123-XXX-XXXX): ");

    // Put the phone number into a string
    String Phone_Number = Input_PhoneNumber.nextLine();
    // close scanner
    Input_PhoneNumber.close();

    // Use Guava Splitter
    List<String> Converted_PhoneNumber =
        Splitter.fixedLength(1)
            .splitToList(Phone_Number)
            .stream()
            .map(t -> {
              if (Character.isAlphabetic(t.codePointAt(0))) {
                return Translate_PhoneNumber.inverse().get(t).asList().get(0);
              } else {
                return t;
              }
            })
            .collect(Collectors.toList());

    System.out.println(String.join("", Converted_PhoneNumber));
  }
}

The code above first creates an ImmutableMultimap with the information of letter and number based on the standard scenario and then use the Splitter with Java 8 inline function syntax to translate the alphabetic phone number. See output:

Enter a phone number with the format (123-XXX-XXXX): 444-CAT-GOOD
444-228-4663
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook