gpt4 book ai didi

java - java中的数字到字母(就像旧手机的键盘)

转载 作者:行者123 更新时间:2023-12-02 04:49:36 24 4
gpt4 key购买 nike

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

例如:输入: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;
}
}
}

最佳答案

这个怎么样?

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 显示的所有示例。

关于java - java中的数字到字母(就像旧手机的键盘),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com