【问题标题】:How to convert characters from a string into numbers (phone number converted)?如何将字符串中的字符转换为数字(电话号码转换)?
【发布时间】:2017-04-20 14:51:07
【问题描述】:

我对如何将 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。

【问题讨论】:

  • 您使用 String [] 的任何具体原因?无论如何,您需要使用一个遍历 char 数组的 for 循环。检查每个 string[] 是否包含该特定字符并相应地替换该字符。
  • @user1211 感谢您的回复。你介意通过如何做到这一点?我对如何使用 for 循环循环字符串感到有些困惑。至于String [],我不太确定......我应该使用char []吗?
  • 嗯,据我所知,你有你的价值数组(可以使用一个字符串[][])。你应该有一个 phoneInput 值。但是你试过什么?您的老师可能更喜欢为您提供的代码(并由 SO 社区进行了一些更新)。
  • PS : CFG 应该输出 123234 ?

标签: java arrays string methods verify


【解决方案1】:

我的解决方案会简单一些。

首先,我不会使用这些数组,而是使用一个二维数组,例如:

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++

对于更多代码,好吧,您需要提供更多信息,因为您也需要做一些工作;)

【讨论】:

  • 谢谢你的回答,但这还是让我很困惑,我想我得和老师谈谈了
  • @guccimanilla 什么部分?我试图留在分析答案上,让您理解并自己尝试,这将是您学习的方式。但我仍然可以为您解释或指导更多。
【解决方案2】:

您可以使用 Collections 代替 String[]。可能地图会很好。但是,由于您使用的是 String[],因此以下代码应该会有所帮助:

for (int i = 0; i < inputToArray.length; i++) {
                if (Arrays.asList(dialTwo).contains(inputToArray[i]))
                    inputToArray[i]=2;
            ...

            }

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

【讨论】:

  • 嗯,好吧,有点理解......我怎么让它打印出来?打印 inputToArray (input= abc) 只需输入 abc。
  • 打印很容易。 System.out.println(Arrays.toString(inputToArray));
  • 只打印原始数组。谢谢你的尝试。
【解决方案3】:

一个简单的方法是映射一个函数来使用 map

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

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

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

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

【讨论】:

    【解决方案4】:
    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
        }
    }
    

    【讨论】:

    • 请解释您发布的代码,“仅代码”的答案没有帮助。
    • List one =(List) Arrays.asList(dialTwo);
    • 以上行将数组转换为列表
    • 因为搜索输入的字符 contains() 方法会有所帮助
    • if(inputToArray[i]>=48&&inputToArray[i]
    【解决方案5】:

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

    添加以下代码:

    /*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);
    

    这应该可以达到目的。

    【讨论】:

    • 请解释您发布的代码,“仅代码”的答案没有帮助。
    • @AxelH 编辑了答案以在 cmets 中包含解释。
    • 好吧,你可以把那些放在代码之外;)并且数值是错误的,a-c = 2,而不是 1。
    • @AxelH 好吧,我还没有在那里进行计算。 ["a-cA-C"] 是正则表达式,它将一次识别一个出现的字母并将其替换为“1”。其他值也是如此。
    • @AxelH 就解释而言,代码最好通过cmets来解释。
    猜你喜欢
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多