简体   繁体   English

美国电话从字母到数字的转换

[英]US phone conversion from letters to numbers

Think I have gone wrong somewhere so I could use some help. 认为我在某个地方出错了,因此可以寻求帮助。 OK the idea is to have the letters you usually find on phones. 好的,想法是让您通常在手机上找到字母。 eg if I wanted to find the number for HAIRCUT it should output like 4247288. 例如,如果我想找到HAIRCUT的号码,它应该输出为4247288。

public class PhoneNumber
{
    String s;
    int i;

    private void PhoneNumber()
    { 
      if ("ABC".contains(""+s.charAt(i))){
          i=2;
        }
          else if ("DEF".contains(""+s.charAt(i))){
              i=3;
            }
            else if ("GHI".contains(""+s.charAt(i))){
                i=4;
            }
            else if ("JKL".contains(""+s.charAt(i))){
                 i=5;
            }
            else if ("MNO".contains(""+s.charAt(i))){
                i=6;
            }
            else if ("PQRS".contains(""+s.charAt(i))){
                i=7;
            }
            else if ("TUV".contains(""+s.charAt(i))){
                i=8;
            }
            else if ("WXYZ".contains(""+s.charAt(i))){
                i=9;
            }                     
    }
    public void decode(){
        PhoneNumber pn = new PhoneNumber();
        pn.decode("HAIRCUT")
        pn.decode("NEWCARS"); 
    }
   }

I know i am missing stuff and even the println at the end but need guidance on how to do this. 我知道我最后都缺少东西,甚至缺少println,但需要有关如何执行此操作的指南。 if you look at the code ABC will come out as 2, DEF as 3 etc. Any ideas? 如果您看一下代码,ABC将显示为2,DEF显示为3,等等。有什么想法吗? I'm very new to Java apologies in advance for my failed attempt. 对于失败的尝试,我对Java道歉非常陌生。

I'd write it like this: 我会这样写:

for (int i=0; i< line.length(); i++){
   convert(line.charAt(i));
}


private static int convert(char c){
    int answer;
    switch(c){
        case 'A': 
        case 'B': 
        case 'C':
            answer = 2;
            break;
        case 'D':
        case 'E':
        case 'F':
            answer = 3;
            break;
        ....
    }
    return answer;
}

I would solve it like this: 我会这样解决:

private static String digits = "22233344455566677778889999";

public static String convert(String input) {
    char[] chars = input.toCharArray();
    for(int i=0; i<chars.length; i++) {
        if(chars[i] >= 'A' && chars[i] <= 'Z')
            chars[i] = digits.charAt(chars[i]-'A');
    }
    return new String(chars);
}

The digits string is actually a mapping between letters from 'A' to 'Z' into digits (first symbol in it corresponds to 'A', second to 'B' and so on). digits字符串实际上是从“ A”到“ Z”的字母到数字之间的映射(其中的第一个符号对应于“ A”,第二个符号对应于“ B”,依此类推)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM