如何将字符串中的字符转换为数字(电话号码转换)?

时间:2016-12-06 03:29:46

标签: java arrays string methods verify

我有点担心我应该如何将char数组中的每个元素替换为数字。

这是我到目前为止的代码:

 public static void main(String []args){

    String[] dialTwo = {"a", "b", "c"};
    String[] dialThree = {"d", "e", "f"};
    String[] dialFour = {"g", "h", "i"};
    String[] dialFive = {"j", "k", "l"};
    String[] dialSix = {"m", "n", "o"};
    String[] dialSeven = {"p", "q", "r", "s"};
    String[] dialEight = {"t", "u", "v"};
    String[] dialNine = {"w", "x", "y", "z"};

    Scanner in = new Scanner(System.in);

    System.out.print("Enter a phone number: ");
    String phoneInput = in.next();
    char[] inputToArray = phoneInput.toCharArray();


    while (!phoneInput.matches("^[a-pA-P0-9]*$")) {
        System.out.println("Not a valid number. Try agian.");
        phoneInput = in.next();
    }

我能够成功验证字符串以防有人想要输入;;';';。

谢谢你的帮助。

我的老师也希望我使用方法类,但我对它有点困惑,所以我的做法有点不同。

所以我想要的输出,如果有人输入“CFG”,它会打印123.

5 个答案:

答案 0 :(得分:1)

我的解决方案会更简单。

首先,我不会使用这些数组,而是使用一个2D数组:

static char[][] keyboard = {
    {'a','b','c'},     //2
    {'d','e','f'},     //3
    {'g','h','i'},     //4
    {'j','k','l'},     //5
    {'m','n','o'},     //6
    {'p','q','r','s'}, //7
    {'t','u','v'},     //8
    {'w','x','y','z'}  //9
};

然后,从这里,我会循环你输入的每个字符。对于每个字符,我会搜索它是哪个数组。您需要的值是index + 2。因此,在keyboard上使用简单的for循环,您可以找到字符的位置并打印您想要的值。当然,数字,空格和符号都有例外。

for each character in input
    if character is numeric
        output ( toNumeric ( character ) )
    else
        index = 0
        while character not found
            if character in array[index]
               output ( index + 2 )
        index++

对于更多代码,您需要提供更多信息,因为您需要稍微工作一点;)

答案 1 :(得分:0)

您可以使用Collections而不是String []。可能地图会很好。但是,因为您正在使用String [],以下代码应该有所帮助:

{{1}}

您需要使用其他if else条件填充...部分,其中您检查inputToArray [i]与其他数组并相应地替换。

答案 2 :(得分:0)

一种简单的方法是将函数映射为使用map

inputToArray.stream().map(/*some function*/).toArray();
private void int /*your function*/(char c){...}

Java上有点生疏,所以不能声称语法是正确的,但基本上映射一个带有char的函数,并将你想要的int返回给你的数组。之后,您所要做的就是编写您要映射的实际函数。

还有很多方法可以解析next返回的字符串,因为在代码中转换为char数组似乎没有任何特殊原因

还应该提到的是,由于没有特定原因,拥有1个长度字符串的数组是相当低效的。您可以轻松使用字符串

答案 3 :(得分:0)

我们可以在这里使用正则表达式(正则表达式)来查找输入中的字母并用相应的整数替换每个字母,直到整个值包含整数。

添加以下代码:

/*Search and replace all alphabets till only numbers are left in the string*/
while(phoneInput.matches("^[a-zA-Z0-9]*$") && !phoneInput.matches("^[0-9]*$")){
        /*
        * Scenario 1:
        * The regex used will search for one occurrence of alphabets a, b & c(both upper and lower case) 
        * and replace with "1". 
        * Same goes down for other values as well.
        */
        phoneInput = phoneInput.replaceFirst("[a-cA-C]", "2"); 
        phoneInput = phoneInput.replaceFirst("[d-fD-F]", "3");
        phoneInput = phoneInput.replaceFirst("[g-iG-I]", "4");
        phoneInput = phoneInput.replaceFirst("[j-lJ-L]", "5");
        phoneInput = phoneInput.replaceFirst("[m-oM-O]", "6");
        phoneInput = phoneInput.replaceFirst("[p-sP-S]", "7");
        phoneInput = phoneInput.replaceFirst("[t-vT-V]", "8");
        phoneInput = phoneInput.replaceFirst("[w-zW-Z]", "9");
    }

System.out.println("The formatted phone number is: " + phoneInput);

这应该有助于达到目的。

答案 4 :(得分:0)

public static void main(String[] args) {
    String[] dialTwo = { "a", "b", "c" };
    String[] dialThree = { "d", "e", "f" };
    String[] dialFour = { "g", "h", "i" };
    String[] dialFive = { "j", "k", "l" };
    String[] dialSix = { "m", "n", "o" };
    String[] dialSeven = { "p", "q", "r", "s" };
    String[] dialEight = { "t", "u", "v" };
    String[] dialNine = { "w", "x", "y", "z" };

    Scanner in = new Scanner(System.in);

    System.out.print("Enter a phone number: ");
    String phoneInput = in.next();
    char[] inputToArray = phoneInput.toCharArray();

    int i = 0;
    while (!phoneInput.matches("^[a-zA-Z0-9]*$")) { // Used to check if any
                                                    // special character is
                                                    // enter in phone number
        System.out.println("Not a valid number. Try agian.");
        phoneInput = in.next();
    }

    List<String> one = (List) Arrays.asList(dialTwo);
    // for converting array into list so that we can use contains method
    // which is not //available in array
    List<String> two = (List) Arrays.asList(dialThree);
    List<String> three = (List) Arrays.asList(dialFour);
    List<String> four = (List) Arrays.asList(dialFive);
    List<String> five = (List) Arrays.asList(dialSix);
    List<String> six = (List) Arrays.asList(dialSeven);
    List<String> seven = (List) Arrays.asList(dialEight);
    List<String> eight = (List) Arrays.asList(dialNine);

    while (i < inputToArray.length) {
        if (inputToArray[i] >= 48 && inputToArray[i] <= 57) {
            // for numeric characters

            System.out.print(inputToArray[i]);
        } else if (one.contains(String.valueOf(inputToArray[i]).toLowerCase()))
        /*
         * searches given character by converting it into lower case in case
         * of capital letters
         */
        {
            System.out.print(1);
        } else if (two.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(2);
        } else if (three.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(3);
        } else if (four.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(4);
        } else if (five.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(5);
        } else if (six.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(6);
        } else if (seven.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(7);
        } else if (eight.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
            System.out.print(8);
        }
        i++;// counter variable for counting number of chars entered
    }
}