java中字母的数字(如旧手机键盘)

时间:2015-03-30 16:02:14

标签: java string numbers letters

就像旧款手机的键盘一样。我应该输入一串数字,程序应该根据这些数字打印出文本。

例如:输入:4448 9666777557777应输出到:ITWORKS。

到目前为止,这是我的代码,但它不打印任何内容。你能告诉我它有什么问题吗?我能做得更好吗?

    Scanner sc = new Scanner(System.in);

    String[] letters = {
            "0",
            "1",
            "ABC",
            "DEF",
            "GHI",
            "JKL",
            "MNO",
            "PQRS",
            "TUV",
            "WXYZ"
    };

    System.out.println("Write something.");
    String numbers = sc.nextLine();

    char[] toChar = numbers.toCharArray();
    int count = 0;

    for (int index = 0; index < toChar.length; index++) {
        if (toChar[index] >= '2' && toChar[index] <= '9') {
            if (index > 0 && toChar[index] == toChar[index - 1]) {
                count++;
            }
            else if (count > 0) {
                System.out.print(letters[toChar[index - 1] - '0'].charAt(count - 1));
                count = 0;              
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

如果我理解你的意图,count只有在当前数字与之前的数字相同时才会增加:

for (int pos = 1, char c = toChar[0], int count = 1; pos <= toChar.length; pos++, count = 1) {

   int n = letters[c - '0'].length;
   while (pos < toChar.length && c == toChar[pos] && count < n) {
       pos++;
       count++;
   }
   System.out.println(letters[c - '0'].charAt(count - 1));
   if (pos < toChar.length - 1) {
       c = toChar[++pos];
   }
}

答案 1 :(得分:1)

这个怎么样?

import java.util.Scanner;

public class Test {
    private static final String[] letters = {
            "0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
    };

    private static char getChar(int digit, int count) {
        while (count > letters[digit].length()) {
            count -= letters[digit].length();
        }

        return letters[digit].charAt(count - 1);
    }

    private static String getString(String input) {
        int lastDigit = 0, count = 1;
        String result = "";

        for (int i = 0; i < input.length(); i++) {
            int currentDigit = input.charAt(i) - '0';
            if (currentDigit >= 2 && currentDigit <= 9) {
                if (lastDigit == 0) {
                    lastDigit = currentDigit;
                } else if (currentDigit == lastDigit) {
                    count++;
                } else {
                    result += getChar(lastDigit, count);

                    lastDigit = currentDigit;
                    count = 1;
                }
            }
        }

        return result + getChar(lastDigit, count);
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Write something");
            System.out.println(getString(scanner.nextLine()));
        }
    }
}

我增强了问题分解。它适用于OP迄今为止所示的所有示例。