How to print numbers as per the phone keypad for any given string

Here we are going to write a java program to convert any String into the phone keypad digits.
eg. ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9)

import java.util.Scanner;

public class PhoneKeypad {
    public static int getNumber(char uppercaseLetter) {
        int number = 0;
        switch (uppercaseLetter) {
        case 'A':
        case 'B':
        case 'C':
            number = 2;
            break;
        case 'D':
        case 'E':
        case 'F':
            number = 3;
            break;
        case 'G':
        case 'H':
        case 'I':
            number = 4;
            break;
        case 'J':
        case 'K':
        case 'L':
            number = 5;
            break;
        case 'M':
        case 'N':
        case 'O':
            number = 6;
            break;
        case 'P':
        case 'Q':
        case 'R':
        case 'S':
            number = 7;
            break;
        case 'T':
        case 'U':
        case 'V':
            number = 8;
            break;
        case 'W':
        case 'X':
        case 'Y':
        case 'Z':
            number = 9;
        }
        return number;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a string to convert in phone keypad: ");
        String stringVal = in.nextLine();

        for (int i = 0; i < stringVal.length(); i++) {
            if (Character.isLetter(stringVal.charAt(i)))
                System.out.print(getNumber(Character.toUpperCase(stringVal
                        .charAt(i))));
            else
                System.out.print(stringVal.charAt(i));
        }
    }
}


Output:

Enter a string to convert in phone keypad: AbCdE
22233

2 comments:

  1. and inverse? user enter AbCdE, for 22233

    ReplyDelete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Front end developer learn from javascript and jquery training in chennai .
    or learn thru Javascript Training in Chennai.
    Nowadays JavaScript has tons of job opportunities on various vertical industry. javascript and jquery training in chennai

    ReplyDelete