将字母电话号码转换为数字

时间:2018-11-07 05:46:47

标签: java wrapper

我正在用Java编写一个程序,该程序需要从用户那里获取一个数字电话号码,例如:555-GET-FOOD,然后打印所有号码555-438-3663。

我遇到了一些问题,因为我的程序只打印一个数字,而不是全部。另外,如何使用户可以在输入中输入破折号,例如:555-GET-FOOD。

这是我到目前为止所做的:

import java.util.*;
public class NumberTranslator {

public static void main(String[] args) {
    // Create Scanner for user input
    Scanner input = new Scanner(System.in);

    // Ask the user to enter the phone number
    System.out.println("Please enter the Phone number in this format: (555-XXX-XXXX) ");

    // Save the phone number into a string
    String phoneNumber = input.nextLine();
    //phoneNumber = phoneNumber.substring(0, 3) + "-" + phoneNumber.substring(3,6)+"-"+phoneNumber.substring(6,10)+"-";

    phoneNumber = phoneNumber.toUpperCase();
    long phoneNumberTranslated = fullPhoneNumber(phoneNumber);

    System.out.println(phoneNumberTranslated);
}

public static long fullPhoneNumber(String phoneNumber) {

    long number = 0;
    int strLength = phoneNumber.length();

    for(int i = 0; i < strLength; i++) {

        char letter = phoneNumber.charAt(i);

        if(Character.isLetter(letter)) {

            switch(letter) {
            case 'A' : case 'B' : case 'C' : number = 2; break;
            case 'D' : case 'E' : case 'F' : number = 3; break;
            case 'G' : case 'H' : case 'I' : number = 4; break;
            case 'J' : case 'K' : case 'L' : number = 5; break;
            case 'M' : case 'N' : case 'O' : number = 6; break;
            case 'P' : case 'Q' : case 'R' : case 'S' : number = 7; break;
            case 'T' : case 'U' : case 'V' : number = 8; break;
            case 'W' : case 'X' : case 'Y' : case 'Z' : number = 9; break;
            }
        }

        else if(Character.isDigit(letter)) {
             Character.getNumericValue(letter);
        }
        else {
            System.out.println("Invalid character!");
        }
    }
    return number;
}
}

我得到的输出如下:

请以以下格式输入电话号码:(555-XXX-XXXX)
555getfood
3

5 个答案:

答案 0 :(得分:1)

我建议您仅为此创建一个地图

Map<Character, String> numbers = new HashMap <Character, String> ();
numbers.put('A', "1" );
numbers.put('B', "1" );
numbers.put('C', "1" );
numbers.put('D', "2" );
numbers.put('E', "2" );
numbers.put('F', "2" );
// etc

for (char c: phoneNumber.toCharArray()) {
    String val = numbers.get (c);
    if (val == null) val = String.valueOf(c);  // if no mapping use as it is
    System.out.print (val);
}

答案 1 :(得分:1)

让我们更新您的代码以使其正常工作:

public static longfullPhoneNumber(String phoneNumber)

更改为:

public static String fullPhoneNumber(String phoneNumber)

,然后在此函数中添加其他result变量:

StringBuilder result = new StringBuilder();

更新您的else if语句:

else if (Character.isDigit(letter)) {
    number = Character.getNumericValue(letter);
}

您已从Char转换为int,但没有保存结果。

然后在for循环的最后,收集我们的结果:

result.append(String.valueOf(number));

因此,最终代码如下:

public class NumberTranslator  {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // Ask the user to enter the phone number
    System.out.println("Please enter the Phone number in this format: (555-XXX-XXXX) ");

    // Save the phone number into a string
    String phoneNumber = input.nextLine();
    // phoneNumber = phoneNumber.substring(0, 3) + "-" +
    // phoneNumber.substring(3,6)+"-"+phoneNumber.substring(6,10)+"-";

    phoneNumber = phoneNumber.toUpperCase();
    String phoneNumberTranslated = fullPhoneNumber(phoneNumber);

    System.out.println(phoneNumberTranslated);
  }

  public static String fullPhoneNumber(String phoneNumber) {

    StringBuilder result = new StringBuilder();

    long number = 0;
    int strLength = phoneNumber.length();

    for (int i = 0; i < strLength; i++) {

      char letter = phoneNumber.charAt(i);

      if (Character.isLetter(letter)) {

        switch (letter) {
          case 'A': case 'B': case 'C': number = 2; break;
          case 'D': case 'E': case 'F': number = 3; break;
          case 'G': case 'H': case 'I': number = 4; break;
          case 'J': case 'K': case 'L': number = 5; break;
          case 'M': case 'N': case 'O': number = 6; break;
          case 'P': case 'Q': case 'R': case 'S': number = 7; break;
          case 'T': case 'U': case 'V': number = 8; break;
          case 'W': case 'X': case 'Y': case 'Z': number = 9; break;
        }
      }

      else if (Character.isDigit(letter)) {
        number = Character.getNumericValue(letter);
      } else {
        System.out.println("Invalid character!");
      }
      result.append(String.valueOf(number));
    }
    return result.toString();
  }
}

答案 2 :(得分:0)

您遇到的问题是您没有添加号码-每次都覆盖它。在循环的每次迭代期间,将number设为String并将相应的数字附加到结果字符串可能会更容易。

此外,在“ else if”中,您对表达式不执行任何操作-您必须将该值存储在某个变量中,否则该值将不会保存在任何地方。

最后,要让用户输入破折号,只需在检查字符是否为“-”的地方添加另一个“ else if”,如果是,则在结果字符串后附加破折号。

答案 3 :(得分:0)

首先,您需要验证您的输入。您可以使用正则表达式模式进行验证。关于您的输入格式:555​​-XXX-XXXX,您可以使用以下正则表达式:555-[a-zA-Z]{3}-[a-zA-Z]{4}

在函数fullPhoneNumber中,它应该返回String而不是long。

检查我的代码如下:

public static void main(String[] args) {
    // Create Scanner for user input
    Scanner input = new Scanner(System.in);

    // Ask the user to enter the phone number
    System.out.println("Please enter the Phone number in this format: (555-XXX-XXXX) ");

    // Save the phone number into a string
    String phoneNumber = input.nextLine();
    // phoneNumber = phoneNumber.substring(0, 3) + "-" +
    // phoneNumber.substring(3,6)+"-"+phoneNumber.substring(6,10)+"-";
    if (validate(phoneNumber)) {
        phoneNumber = phoneNumber.toUpperCase();
        String phoneNumberTranslated = fullPhoneNumber(phoneNumber);
        System.out.println(phoneNumberTranslated);
    } else {
        System.out.println("Wrong phone number format.");
        return;
    }

}

private static boolean validate(String phoneNumber) {
    Pattern r = Pattern.compile("555-[a-zA-Z]{3}-[a-zA-Z]{4}");

    // Now create matcher object.
    Matcher m = r.matcher(phoneNumber);
    if (m.find()) {
        return true;
    }
    return false;
}

public static String fullPhoneNumber(String phoneNumber) {

    String result = "5555-";
    String suffix = phoneNumber.substring("555-".length());
    for (int i = 0; i < suffix.length(); i++) {

        char letter = suffix.charAt(i);

        if (Character.isLetter(letter)) {

            switch (letter) {
            case 'A':
            case 'B':
            case 'C':
                result += "2";
                break;
            case 'D':
            case 'E':
            case 'F':
                result += "3";
                break;
            case 'G':
            case 'H':
            case 'I':
                result += "4";
                break;
            case 'J':
            case 'K':
            case 'L':
                result += "5";
                break;
            case 'M':
            case 'N':
            case 'O':
                result += "6";
                break;
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
                result += "7";
                break;
            case 'T':
            case 'U':
            case 'V':
                result += "8";
                break;
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
                result += "9";
                break;
            }
        } else if (letter == '-') {
            result += "-";
        }
    }
    return result;
}

答案 4 :(得分:-1)

//try this...this will definitely work
import java.util.Scanner;
public class phonenumber 
{
  char letter2num(char ch)
{
    switch (ch)
    {
        case 'A':
        case 'B':
        case 'C':
        case 'a':
        case 'b':
        case 'c':
            return '2';
        case 'D':
        case 'E':
        case 'F':
        case 'd':
        case 'e':
        case 'f':
            return '3';
        case 'G':
        case 'H':
        case 'I':
        case 'g':
        case 'h':
        case 'i':
            return '4';
        case 'J':
        case 'K':
        case 'L':
        case 'j':
        case 'k':
        case 'l':
            return '5';
        case 'M':
        case 'N':
        case 'O':
        case 'm':
        case 'n':
        case 'o':
            return '6';
        case 'P':
        case 'Q':
        case 'R':
        case 'S':
        case 'p':
        case 'q':
        case 'r':
        case 's':
            return '7';
        case 'T':
        case 'U':
        case 'V':
        case 't':
        case 'u':
        case 'v':
            return '8';
        case 'W':
        case 'X':
        case 'Y':
        case 'Z':
        case 'w':
        case 'x':
        case 'y':
        case 'z':
            return '9';
        default:
            return ch;
    }
}
public static void main(String[] args) 
{
    Scanner joey = new Scanner(System.in);
    System.out.print("\nEnter phone number (xxx-xxx-xxxx): ");
    String goku = joey.nextLine();
    char[] gohan = goku.toCharArray();
    phonenumber number= new phonenumber();
    if(goku.length() != 10)
        System.out.print("Not phone number!! ");
    else
    {
        for(int i=0; i<10 ;i++)
            gohan[i]=number.letter2num(gohan[i]);
    }
    goku=new String(gohan);
    goku = goku.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");
    System.out.print("phone number: "+goku);
    joey.close();
}

}