Java program to convert mobile number pad to characters

This post is about Java program to convert mobile number pad to characters.

Example
=========
Here is an image of mobile phone num pad. For every numbers except 1, there are certain character value associated with that. # is used to separate the letters.


If the user presses 44#44, it should print HH

Logic of the program
================

  • A hashmap is used to store the number and its corresponding characters.
  • If the user presses the number n times before pressing #, the nth character is selected from the hashmap.
  • if n is greater than number of characters, select the character which is at the position (n mod number of characters)

Program
========

The java program is as follows:

import java.util.HashMap;
  
 public class MobilePhoneNumPadToCharacters {
  
        public static void main(String[] args) {
         System.out.println(returnWords("222#2#8")); //CAT
         System.out.println(returnWords("5555#2#888888#2222"));  //JAVA
 }
       
       
        public static String returnWords(String str)
        {
               HashMap<Character, String> mobileNumPad = new HashMap<Character, String>();
               
                mobileNumPad.put('2', "ABC");
                mobileNumPad.put('3', "DEF");
                mobileNumPad.put('4', "GHI");
                mobileNumPad.put('5', "JKL");
                mobileNumPad.put('6', "MNO");
                mobileNumPad.put('7', "PQRS");
                mobileNumPad.put('8', "TUV");
                mobileNumPad.put('9', "WXYZ");
                mobileNumPad.put('0'," ");
  
                String[] tokens = str.split("#");
                String out = "";
               
                for (int i = 0; i < tokens.length; i++)
                {
                    char temp = tokens[i].charAt(0);
                    String getWords = mobileNumPad.get(temp);
                    int length = tokens[i].length();
            
                    if(length>getWords.length())
                    {
                      length = length%getWords.length();
                    }
                   
                    if(length == 0)
                    {
                      length = getWords.length();
                    }
                    out = out+getWords.charAt(length-1);
                   
                }
               
                return out;
        }
 }

Good to Read
===========

1) Linked list implementation in java
2) Binary tree implementation in java
3) Java program to check whether string contains unique characters

Comments

  1. If it is, it formats the number into the standard "(XXX) XXX-XXXX" format.
    If the input is not 10 digits long, it returns an error message. Latent Resident Artist This blog is informative and useful.

    ReplyDelete

Post a Comment

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++