Alpha Phrase to phone number using Java
Posted by Samath
Last Updated: January 17, 2024

To make telephone numbers easier to remember, some companies use letters to show their telephone number. For example, the telephone number 438-5626 can be shown as GET-LOAN. In some cases, to make a telephone number meaningful, companies might use more than seven letters. For example, 225-5466 can be displayed as CALL-HOME, which uses eight letters. Write a program that prompts the user to enter a telephone number expressed in letters and outputs the corresponding telephone number in digits. If the user enters more than eight letters, then process only the first seven letters. Also, output the – (hyphen) after the third digit. Allow the user to use uppercase and lowercase letters. Moreover, your program should process as many telephone numbers as the user wants.

Solution:

import java.util.Scanner;

public class PhoneNumber {
    public static void main(String args[]) {
    
    String phoneNumber;
    char phoneDigit;
    Scanner scan = new Scanner(System.in);
    
 for(;;)
 {
    System.out.print("\nEnter a phone number in letters only (or press 1 to exit): ");
    phoneNumber = scan.next();
    
 if(phoneNumber.equals("1"))
 {
     break;
 }
for(int i = 0; i < 7; i++)
{
      phoneDigit = phoneNumber.charAt(i);
     
      if(i == 3)
         System.out.print("-");
if(phoneDigit >= 'A' && phoneDigit <= 'Z' || phoneDigit >= 'a' && phoneDigit <= 'z')
{
switch(phoneDigit)
{
         case 'A':
         case 'a':
         case 'B':
         case 'b':
         case 'C':
         case 'c':
             System.out.print("2");
             break;
         case 'D':
         case 'd':
         case 'E':
         case 'e':
         case 'F':
         case 'f':
            System.out.print("3");
             break;
         case 'G':
         case 'g':
         case 'H':
         case 'h':
         case 'I':
         case 'i':
             System.out.print("4");
             break;
             
         case 'J':
         case 'j':
         case 'K':
         case 'k':
         case 'L':
         case 'l':
             System.out.print("5");
             break;
         case 'M':
         case 'm':
         case 'N':
         case 'n':
         case 'O':
         case 'o':
             System.out.print("6");
             break;
         case 'P':
         case 'p':
         case 'Q':
         case 'q':
         case 'R':
         case 'r':
         case 'S':
         case 's':
             System.out.print("7");
             break;
             
         case 'T':
         case 't':
         case 'U':
         case 'u':
         case 'V':
         case 'v':
             System.out.print("8");
             break;
             
         case 'W':
         case 'w':
         case 'X':
         case 'x':
         case 'Y':
         case 'y':
         case 'Z':
         case 'z':
            System.out.print("9");
             break;             
}
}
}
}
}
}