Your phone keypad shows certain alphabets mapped to digits a

Your phone keypad shows certain alphabets mapped to digits as follows:

ABC(1), DE(2), FGHI(3), JKL(4), MNOP(5), QR(6), ST(7), UVW(8), XYZ(9).

Write a Java program called KeyTranslator, which prompts the user for a String (which has to be entered in uppercase, but you don’t have to worry about making the program check for this), and converts to a sequence of phone keypad digits. This program should work for any String entered into the program. Use a nested-if (or switch-case might be easier) in this exercise, as well as the java.util.Scanner library to take in the String input. Also, you will have to use the .charAt() method for Strings (see class example to find out how this works).

Solution

import java.util.Scanner;
public class KeyTranslator {

public static void main(String[] args) {
KeyTranslator ob = new KeyTranslator();
ob.convert();
}

private void convert()
{
       String input;
Scanner in = new Scanner(System.in);
System.out.print(\"Please enter a String: \");
input = in.next();

int digit = 0;
for(int i=0;i<input.length();i++)
{
switch (input.toUpperCase().charAt(i))
{
case \'A\': case \'B\': case \'C\': digit = 1; break;
case \'D\': case \'E\': digit = 2; break;
case \'F\': case \'G\': case \'H\': case \'I\': digit = 3; break;
case \'J\': case \'K\': case \'L\': digit = 4; break;
case \'M\': case \'N\': case \'O\': case \'P\': digit = 5; break;
case \'Q\': case \'R\': digit = 6; break;
case \'S\': case \'T\': digit = 7; break;
               case \'U\': case \'V\': case \'W\': digit = 8; break;
case \'X\': case \'Y\': case \'Z\': digit = 9; break;
}
System.out.print(digit);
}
System.out.println();
}
}

Your phone keypad shows certain alphabets mapped to digits as follows: ABC(1), DE(2), FGHI(3), JKL(4), MNOP(5), QR(6), ST(7), UVW(8), XYZ(9). Write a Java progr

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site