在输出中的每个数字之间实现连字符

时间:2017-03-13 02:56:23

标签: java

所以我正在编写一个模仿电话键盘的程序,而它会将一串文本转换为整数:abc(2),def(3),ghi(4),jkl(5),mno (6),pqrs(7),tuv(8),wxyz(9)。除了输出之外,数字之间应该有连字符( - )。

示例输入:Alabama

输出:2-5-2-2-2-6-2

但我的代码只输出2522262。我该如何正确格式化?

import java.util.Scanner;

public class PhoneKeypad {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    System.out.println(getNumbers(str));
}

private static final char[] DIGITS = ( 
      // ABC     DEF
        "222" + "333"
    + // GHI     JKL     MNO
        "444" + "555" + "666"
    + // PQRS     TUV     WXYZ
        "7777" + "888" + "9999").toCharArray();

public static String getNumbers(CharSequence   s) {
    StringBuilder result = new StringBuilder(s.length());
    for (int i = 0; i < s.length(); i++) {
        char c = Character.toUpperCase(s.charAt(i));
        if ('A' <= c && c <= 'Z') {
            result.append(DIGITS[c - 'A']);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在每个数字后添加-。我看到的最简单的方法,改变

result.append(DIGITS[c - 'A']);

result.append(DIGITS[c - 'A']).append('-');

然后在您返回时删除最后一个-

public static String getNumbers(CharSequence s) {
    StringBuilder result = new StringBuilder(s.length() * 2); // <-- digit-digit...
    for (int i = 0; i < s.length(); i++) {
        char c = Character.toUpperCase(s.charAt(i));
        if ('A' <= c && c <= 'Z') {
            result.append(DIGITS[c - 'A']).append('-');
        }
    }
    if (result.length() > 1) {
        result.setLength(result.length() - 1);
    }
    return result.toString(); // <-- Don't forget to return the result.
}

如果您传入s,可能会觉得更容易,您可以拨打toUpperCase()toCharArray(),然后使用for-each循环。像,

public static String getNumbers(String s) {
    StringBuilder result = new StringBuilder(s.length() * 2);
    for (char c : s.toUpperCase().toCharArray()) {
        if (c >= 'A' && c <= 'Z') { // <-- I find this test easier to read, 
                                    //     but that's just my opinion.
            result.append(DIGITS[c - 'A']).append('-');
        }
    }
    if (result.length() > 1) {
        result.setLength(result.length() - 1);
    }
    return result.toString();
}