Ciaran
Ciaran

Reputation: 695

map letters to digits C#

I am trying to write a simple program which maps letters to their equivalent digits like you would get on a phones keypad. For example aghk = 2445. I cant seem to get the program to work properly. what I have so far is below. I am using the MVC (model view controller) pattern. The problem I am getting is that if I enter one letter it will give the correct digit, but as soon as I enter more than one digit no output appears. Any help that you could give me on how to solve this would be appreciated.

namespace MapKeyPad
{
    class Model
    {
        public String ReadKey(String usrInput)
        {
            usrInput = usrInput.ToLower();
            int Len = usrInput.Length;
            int i = 0;

            if (usrInput == "a" || usrInput == "b" || usrInput == "c")
            {
                Console.Write("1");
            }

            else if (usrInput == "d" || usrInput == "e" || usrInput == "f")
            {
                Console.Write("2");
            }

            else if (usrInput == "g" || usrInput == "h" || usrInput == "i")
            {
                Console.Write("3");
            }

            return "";
        }
    }
}

Upvotes: 0

Views: 232

Answers (3)

WAQ
WAQ

Reputation: 2626

@giorgi answer is very well described but if you want to write a generic code then you might consider using the ASCII value of each character being typed and subtract 96 (a's ASCII value is 97) this will give u values for all small case letters from a-z. Similarly write your logic for capital case letters as well

Upvotes: 0

Giorgi Moniava
Giorgi Moniava

Reputation: 28664

The problem I am getting is that if i enter one letter it will give the correct digit, but as soon as i enter more than one digit no output appears.

Well this is because due to your comparison logic. See here:

        if (usrInput == "a" || usrInput == "b" || usrInput == "c")

You are comparing the whole string against a single letter say "a". You need something like this:

foreach (char c in usrInput)
{
      if (c == 'a' || c == 'b' || c == 'c')
      {
       Console.Write("1");
      } // etc. do other comparisons similarly
      ...
} 

Upvotes: 4

Igoris
Igoris

Reputation: 1650

Try something like this:

    var usrInput = usrInput.ToLower();
    foreach(var letter in usrInput)
    {
       if (letter == 'a' || letter == 'b' || letter == 'c')
       {
           Console.Write("1");
       }

       else if (letter == 'd' || letter == 'e' || letter == 'f')
       {
           Console.Write("2");
       }

       else if (letter == 'g' || letter == 'h' || letter == 'i')
       {
           Console.Write("3");
       }
    }

Upvotes: 1

Related Questions