开发者

Converting letters to digits using phone standard

开发者 https://www.devze.com 2022-12-19 18:27 出处:网络
Only starting java, need a program to convert the letter on the button of a mobile phone into a number.

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" |开发者_Go百科| letter== "V")
         {
            System.out.println("7");    
         }    

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


    }

}


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.


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'));
}


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;

    }

}


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?


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 ?


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.


frankly switch would be easier to look at; however, if you prefer 'if..else' have you considered the below?

The code below should run well as per the requirements.

--------------------------------------------------------------------

import java.util.*;

public class Question3Mod 
{
    public static void main(String[] args) 
    {
        Scanner kb = new Scanner(System.in);
        System.out.println("Enter phone number in letters: ");
        String telInput = kb.nextLine();
        int i;
        int count = 0;

        System.out.print("Phone number you entered is: ");

        for(i = 0; i <= telInput.length()-1; i++)
        {
            if(count == 3)
            {
                System.out.print("-");
            }
            char phoneChar = telInput.charAt(i);
            if (count == 7)
            {
                System.out.println("");
                break;
            }
            else{
                if( 
                    phoneChar == 'A' || phoneChar == 'a' ||
                    phoneChar == 'B' || phoneChar == 'b' ||
                    phoneChar == 'C' || phoneChar == 'c') 
                {
                    System.out.print("2");
                    count++;
                }
                else if(
                        phoneChar == 'D' || phoneChar == 'd' ||
                        phoneChar == 'E' || phoneChar == 'e' ||
                        phoneChar == 'F' || phoneChar == 'f')
                {
                    System.out.print("3");
                    count++;
                }
                else if(
                        phoneChar == 'G' || phoneChar == 'g' ||
                        phoneChar == 'H' || phoneChar == 'h' ||
                        phoneChar == 'I' || phoneChar == 'i')
                {
                    System.out.print("4");
                    count++;
                }
                else if(
                        phoneChar == 'J' || phoneChar == 'j' ||
                        phoneChar == 'K' || phoneChar == 'k' ||
                        phoneChar == 'L' || phoneChar == 'l')
                {
                    System.out.print("5");
                    count++;
                }
                else if(
                        phoneChar == 'M' || phoneChar == 'm' ||
                        phoneChar == 'N' || phoneChar == 'n' ||
                        phoneChar == 'O' || phoneChar == 'o')
                {
                    System.out.print("6");
                    count++;
                }
                else if(
                        phoneChar == 'P' || phoneChar == 'p' ||
                        phoneChar == 'Q' || phoneChar == 'q' ||
                        phoneChar == 'R' || phoneChar == 'r' ||
                        phoneChar == 'S' || phoneChar == 's')
                {
                    System.out.print("7");
                    count++;
                }
                else if(
                        phoneChar == 'T' || phoneChar == 't' ||
                        phoneChar == 'U' || phoneChar == 'u' ||
                        phoneChar == 'V' || phoneChar == 'v')
                {
                    System.out.print("8");
                    count++;
                }
                else if(
                        phoneChar == 'W' || phoneChar == 'w' ||
                        phoneChar == 'X' || phoneChar == 'x' ||
                        phoneChar == 'Y' || phoneChar == 'y' ||
                        phoneChar == 'Z' || phoneChar == 'z')
                {
                    System.out.print("9");
                    count++;
                }
            }
        }     
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消