In: Computer Science
To make telephone numbers easier to remember, some companies use letters to show their telephone number. For example, using letters, 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.
Instructions
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 seven letters, then process only the first seven letters.
Also output the - (hyphen) after the third digit.
Allow the user to use both uppercase and lowercase letters as well as spaces between words.
Moreover, your program should process as many telephone numbers as the user wants.
Use the dialpad below for reference:
The program should accept input and produce output similar to the example program execution below.
Enter Y/y to convert a telephone number from letters to digits. Enter any other letter to terminate the program. Y Enter a telephone number using letters: Hello world The corresponding telephone number is: 435-5696 To process another telephone number, enter Y/y Enter any other letter to terminate the program. z
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
char Arr[][]=new char[8][4];
Arr[0][0]='A';
Arr[0][1]='B';
Arr[0][2]='C';
Arr[1][0]='D';
Arr[1][1]='E';
Arr[1][2]='F';
Arr[2][0]='G';
Arr[2][1]='H';
Arr[2][2]='I';
Arr[3][0]='J';
Arr[3][1]='K';
Arr[3][2]='L';
Arr[4][0]='M';
Arr[4][1]='N';
Arr[4][2]='O';
Arr[5][0]='P';
Arr[5][1]='Q';
Arr[5][2]='R';
Arr[5][3]='S';
Arr[6][0]='T';
Arr[6][1]='U';
Arr[6][2]='V';
Arr[7][0]='W';
Arr[7][1]='X';
Arr[7][2]='Y';
Arr[7][3]='Z';
System.out.println("Enter Y/y to convert a telephone
number from letters to digits.\nEnter any other letter to terminate
the program.");
char x=sc.next().charAt(0);
if(x=='y'||x=='Y')
{
System.out.println("Enter a telephone number using
letters:");
}
while(x=='y'||x=='Y')
{sc.nextLine();
String str=sc.nextLine();
str = str.replaceAll("\\s", "");
str=str.toUpperCase();
str=shorten(str,7);
int num=0;
for(int i=0;i<7;i++)
{
for(int j=0;j<8;j++)
{
for(int k=0;k<4;k++)
{
if(str.charAt(i)==Arr[j][k])
{num=num*10+j+2;}
}
}
}
String res=Integer.toString(num);
res=res.substring(0,3)+"-"+res.substring(3,7);
System.out.println("The corresponding telephone number
is:"+res);
System.out.println("To process another telephone
number, enter Y/y \nEnter any other letter to terminate the
program.");
x=sc.next().charAt(0);
}
}
public static String shorten(String s,int len)
{
if (s == null)
return null;
if (s.length() > len)
s = s.substring(0, len) + "";
return s;
}
}