首先,我正在尝试构建一个程序,根据输入的电话号码打印出所有可能的字母组合。
我的问题是我无法让我的递归函数工作,我得到了跟随错误堆栈。错误指向第 46 行是 "recursion("", line);和第 65 行是for (int i = 0; i < letters.length(); i++) {
Exception in thread "main" java.lang.NullPointerException
at exercise.test.PhoneNumberCombo.recursion(PhoneNumberCombo.java:46)
at exercise.test.PhoneNumberCombo.main(PhoneNumberCombo.java:65)
这是我的代码:
import org.apache.commons.io.IOUtils;
public class PhoneNumberCombo {
static void recursion(String combination, String next_digits) {
List<String> result = new ArrayList<String>();
Map<String, String> phone = new HashMap<String, String>() {{
put("2", "abc");
put("3", "def");
put("4", "ghi");
put("5", "jkl");
put("6", "mno");
put("7", "pqrs");
put("8", "tuv");
put("9", "wxyz");
}};
// BASE CASE no more digits found
if (next_digits.length() == 0) {
// the combination is built
result.add(combination);
System.out.println(result);
}
else {
String digit = next_digits.substring(0, 1);
String letters = phone.get(digit);
for (int i = 0; i < letters.length(); i++) {
String letter = phone.get(digit).substring(i, i + 1);
recursion(combination + letter, next_digits.substring(1));
}
}
}
千巷猫影
相关分类