tags:

views:

159

answers:

7

Only starting java, need a program to convert the letter on the button of a mobile phone into a number.

e.g. a=2 or v=8. I've tried a few approaches, it compiles alright but wont give me the answer?

public class digits

{
    public static void main (String letter)

    {

        if (letter=="A" || letter=="B" || letter== "C")
         {
            System.out.println("1");
         }

         else if(letter=="D" || letter=="E" || letter== "F")
         {
            System.out.println("2");
         }

        else if (letter=="G" || letter=="H" || letter== "I")
         {
            System.out.println("3");   
         }
         else if (letter=="J" || letter=="K" || letter== "L")
         {
            System.out.println("4");    
         }
         else if (letter=="M" || letter=="N" || letter== "O")
         {
            System.out.println("5");    
         }    

        else if (letter=="P" || letter=="Q" || letter== "R" || letter== "S")
         {
            System.out.println("6");    
         }    

        else if (letter=="T" || letter=="U" || letter== "V")
         {
            System.out.println("7");    
         }    

         else if (letter=="W" || letter=="X" || letter== "Y" || letter== "Z")
         {
            System.out.println("9");    
         }    


    }

}
A: 

Whilst there may be ways to improve the layout and approach to this problem, if you want to make it work, I would look at doing string comparison with the "==" operator. Look at .equals() for strings instead. I am assuming you are using Java here, but your tag suggests jquery. Could you clarify what you are using?

chillysapien
+1  A: 
  • if it should be Main, your signature of Main is wrong (must be a String[])
  • can you verify your input letter?
  • you should rather go for char than for string (and a switch instead!)
  • consider case-insensitive-checking!
Andreas Niedermair
consider the fact it's "main", not "Main" ;)
Photodeus
dahaha ... :) i took his question case-insensitive :) will update! thx
Andreas Niedermair
+7  A: 

you should use the equals method, not checking with ==.

By the way to avoid strange things it would be better to get just the first character of the string and check it with normal comparisons:

public static void main(String[] args)
{
     char c = args[0].toLowerCase().charAt(0);

     if (c == 'a' || c == 'b' || c == 'c')
          ....
}

Then think about the fact that the main method supplies an array of strings, not a single one.

A more elegant approach should consider the fact that letters are grouped by ABC DEF GHI JKL MNO PQRS TUV WXYZ

so you can directly divide the input character:

char c = args[0].toLowerCase().charAt(0);
int which = (c - 'a') / 3;

if (which <= 5)
  return which;
else if (which == 8)
  return which - 1;
else // can be S T U or V W X
  if (which % 3 == 0) // it's S or V
    return which - 1; // return the previous key
  else
    return which;

EDIT: Mind that this approach returns a zero-based index of the keypad.

Jack
If you're going to use `char` you're better off with a switch statement, the resultant code will be much clearer...
Mark E
yep, but i was writing this different approach.. that's why I didn't care about switch :D cause a chain of comparisons can be quite reduced assuming that pattern is quite regular..
Jack
I would like to know why people just click down vote without explaining them selves. It would be useful to improve things..
Jack
A: 

You know that A is different from a, right? So, if you want to go that way you should add on more || clause for every letter. For example:

if (letter=="A" || letter=="B" || letter== "C" || letter=="a" || letter=="b" || letter== "c")

or just add toUpper to your input letter ?

anthares
+1  A: 

Your class has the wrong method signature for the main method. main always takes a String array.

Also, considering using char with a switch statement.

Here's an example of that (untested at the moment) put into a separate function:

public class digits
{
    public static int phoneCharToDigit (char letter)
    {
        letter = Character.toUpperCase(letter);
        int value = 0;

        switch(letter) {
            case 'A':
            case 'B':
            case 'C':
                // Yes, 2, your original code was wrong; there are no letters on 1
                value = 2;
                break;

            case 'D':
            case 'E':
            case 'F':
                value = 3;
                break;

            case 'G':
            case 'H':
            case 'I':
                value = 4;
                break;

            case 'J':
            case 'K':
            case 'L':
                value = 5;
                break;

            case 'M':
            case 'N':
            case 'O':
                value = 6;
                break;

            case 'P':
            case 'Q':
            case 'R':
            case 'S':
                value = 7;
                break;

            case 'T':
            case 'U':
            case 'V':
                value = 8;
                break;

            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
                value = 9;
                break;

        }
        return value;

    }

}
R. Bemrose
+3  A: 

I would consider that, in order to encapsulate this logic, is better using an object:

class TelephoneKeyboard {

    private final Map<Character, Integer> mapping;

    public TelephoneKeyboard() {
        mapping = new HashMap<Character, Integer>();
    }

    public TelephoneKeyboard addKeys(Integer i, String characters) {
        for (Character c : characters.toCharArray()) {
            mapping.put(c, i);
        }

        return this;
    }

    public int getKey(char ch) {
        return mapping.get(ch);
    }
}

Testcase:

@Test
public void keyboardTest() {
    TelephoneKeyboard telephoneKeyboard = new TelephoneKeyboard();
    telephoneKeyboard.addKeys(2, "abc");
    telephoneKeyboard.addKeys(3, "def");
    telephoneKeyboard.addKeys(4, "ghi");
    telephoneKeyboard.addKeys(5, "jkl");
    // etc etc
    assertEquals(2, telephoneKeyboard.getKey('a'));
}
dfa
A: 

While maybe not a direct answer to your question, the following is something you would benefit greatly from improving in:

In your main function body you are mixing the business logic part (printing the result to the stdout) with the task specific details. By doing this you create code that is very difficult to maintain. What if you instead want to put the number in a text field instead of printing it? Then you would have to change all the println statements. What if you sometimes want to print and sometimes update a text field? Would you add some if test every place instead?

By mixing business logic (and I use that as a quite loosely defined term, how to process results) in the code it becomes more difficult to test. The principle of KISS is taught for a reason, and you would do wise of trying to avoid learning it the hard way :)

Maybe the above is not so clear, what I mean is that if your code had been written in the following way:

public class digits

{
    public static int main letterToMobileDigit(char letterUpperOrLowerCase)
    {
        char letter = letterUpperOrLowerCase.toLowerCase();

        if (letter=='a' || letter=='b' || letter== 'c')
         {
            return 1;
         }

         else if(letter=='d' || letter=='e' || letter== 'f')
         {
            return 2;
         }

        else if (letter=='g' || letter=='h' || letter== 'i')
         {
            return 3;
         }
         else if (letter=='j' || letter=='k' || letter== 'l')
         {
            return 4;
         }
         else if (letter=='m' || letter=='n' || letter== 'o')
         {
            return 5;
         }    

        else if (letter=='p' || letter=='q' || letter== 'r' || letter== 's')
         {
            return 6;
         }    

        else if (letter=='t' || letter=='u' || letter== 'v')
         {
            return 7;
         }    

         else if (letter=='w' || letter=='x' || letter== 'y' || letter== 'z')
         {
            return 9;
         }    

         System.err.println("invalid char " + letter); // not the best or most elegant error handling, consider improving
         return -1;
    }

    public static void main (String letter)
    {
        System.out.println(letterToMobileDigit(letter.charAt(0)))
    }


}

you have code that is much easier to change, test and read.

The principle of separating logic where it belongs is an extremely important skill, and there is no good reason for not always practising it.

hlovdal