首先,我正在尝试构建一个程序,该程序根据输入的电话号码打印出所有可能的字母组合。
我的问题是我无法使递归函数正常工作,我得到了跟踪错误堆栈。错误指向第46行为“ recursion("", line);
”和第65行为for (int i = 0; i < letters.length(); i++) {
Exception in thread "main" java.lang.NullPointerException
at JPMorgan.test.PhoneNumberCombo.recursion(PhoneNumberCombo.java:46)
at JPMorgan.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));
}
}
}
public static void main(String[] args) throws IOException {
InputStream phoneInputStream = IOUtils.toInputStream("123456", "UTF-8");
InputStreamReader reader = new InputStreamReader(phoneInputStream);
BufferedReader in = new BufferedReader(reader);
String line = in.readLine();
if (line.length() != 0)
recursion("", line);
}
}
答案 0 :(得分:0)
显然,失败的行表示letters
是null
。例如,对于"0"
地图中不存在的"1"
或phone
或任何其他String
,都会发生这种情况。
您必须处理letters
之后null
为String letters = phone.get(digit)
的情况。是否跳过此String
或抛出有关不适当符号的显式异常。