Telephone keypads have an international standard for mapping the alphabet to the
ID: 3844403 • Letter: T
Question
Telephone keypads have an international standard for mapping the alphabet to the number keys. This can be seen in the image below: Write a program which can take a series of 10 letters and converts them to the corresponding phone number. Input Validation: The input must be exactly 10 characters, no more, no less. Requirements: The output must be formatted in the following format (###) ###-####. You are NOT allowed to use loops or arrays. You may only use coding techniques found in chapters. Your program must work for any input. Sample Output: Enter input: CODEISLIFE Phone Number: (263) 347-5433Explanation / Answer
Please find the required program and output below: Please find the comments against each line for the description:
import java.util.Scanner;
class Test {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter input: ");
String input = scanner.next(); //read the input from user
if(input.length() != 10){ //if the input string length in not 10
System.out.println("Invalid input...It must be 10 characters.");
}else{
input = input.toUpperCase(); //convert input to upper case
String output = "("; //create the output format
output += getNumber(input.charAt(0));
output += getNumber(input.charAt(1));
output += getNumber(input.charAt(2));
output += ") ";
output += getNumber(input.charAt(3));
output += getNumber(input.charAt(4));
output += getNumber(input.charAt(5));
output += "-";
output += getNumber(input.charAt(6));
output += getNumber(input.charAt(7));
output += getNumber(input.charAt(8));
output += getNumber(input.charAt(9));
System.out.println("Phone Number: "+output);
}
}
//returns the corresponding number mapping of an alphabet
public static int getNumber(char c){
switch(c){
case 'A':
case 'B':
case 'C': return 2;
case 'D':
case 'E':
case 'F': return 3;
case 'G':
case 'H':
case 'I': return 4;
case 'J':
case 'K':
case 'L': return 5;
case 'M':
case 'N':
case 'O': return 6;
case 'P':
case 'Q':
case 'R':
case 'S': return 7;
case 'T':
case 'U':
case 'V': return 8;
case 'W':
case 'X':
case 'Y':
case 'Z': return 9;
default :
return -1;
}
}
-------------------------------------------------------------
OUTPUT:
Enter input:
CODEISLIFE
Phone Number: (263) 347-5433
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.