Many companies use telephone numbers like 555-GET-FOOD so the number is easier f
ID: 3817678 • Letter: M
Question
Many companies use telephone numbers like 555-GET-FOOD so the number is easier for their customers to remember. On a standard telephone, the alphabetic letters are mapped to number in the following fashion: 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, an V = 8 W, X, Y, and Z = 9 Write an application that asks the user to enter a 10-character telephone number (in any format such as: XXXXXXXXXX, (XXX) XXX-XXXX, or XXX-XXX-XXXX). The application should display the telephone number with any alphabetic characters that appear in the original translated appropriately to their numeric equivalent. For example, if the user enters 555-GET-FOOD the application should display 555-438-3663.Explanation / Answer
import java.util.HashMap;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
HashMap<Character, Character> hm = new HashMap<Character, Character>();
hm.put('A', '2');
hm.put('B', '2');
hm.put('C', '2');
hm.put('D', '3');
hm.put('E', '3');
hm.put('F', '3');
hm.put('G', '4');
hm.put('H', '4');
hm.put('I', '4');
hm.put('J', '5');
hm.put('K', '5');
hm.put('L', '5');
hm.put('M', '6');
hm.put('N', '6');
hm.put('O', '6');
hm.put('P', '7');
hm.put('Q', '7');
hm.put('R', '7');
hm.put('S', '7');
hm.put('T', '8');
hm.put('U', '8');
hm.put('V', '8');
hm.put('W', '9');
hm.put('X', '9');
hm.put('Y', '9');
hm.put('Z', '9');
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = reader.next();
input = input.toUpperCase();
if(input.contains("(")){
input=input.replace("(", "");
}
if(input.contains(")")){
input=input.replace(")", "");
}
if(input.contains("-")){
input=input.replace("-", "");
}
char[] inputChar = input.toCharArray();
for(int i=3; i<inputChar.length; i++){
inputChar[i] = hm.get(inputChar[i]);
}
input = String.valueOf(inputChar);
StringBuilder sb = new StringBuilder(input);
sb.insert(3, "-");
sb.insert(7, "-");
System.out.println(sb.toString());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.