Java 执行深度优先搜索时的Nullpointerexception

Java 执行深度优先搜索时的Nullpointerexception,java,recursion,nullpointerexception,depth-first-search,Java,Recursion,Nullpointerexception,Depth First Search,假设区域1有三个内容2,3,4,区域2有三个内容1,2,3,区域3有两个内容1,2。m是一个映射,其中键是locationid,值是contentid的列表。例如,area1具有映射(1,{2,3,4})。每个区域选择一个内容并查找所有组合。我使用dfs(递归)来解决这个问题,但是第1行中有一个nullpointerexception。中间层是一个字符串列表,我遍历该列表,它们的类型都是字符串,为什么会出现空指针异常?这是nullpointerexception中的一个特定条件,它不是重复的 p

假设区域1有三个内容2,3,4,区域2有三个内容1,2,3,区域3有两个内容1,2。m是一个映射,其中键是locationid,值是contentid的列表。例如,area1具有映射(1,{2,3,4})。每个区域选择一个内容并查找所有组合。我使用dfs(递归)来解决这个问题,但是第1行中有一个nullpointerexception。中间层是一个字符串列表,我遍历该列表,它们的类型都是字符串,为什么会出现空指针异常?这是nullpointerexception中的一个特定条件,它不是重复的

public static List<String> dfs(String digits,Map<String, List<String>> m) {
        List<String> result = new ArrayList<String>();
        if(digits.length() == 0){
            return result;
        }
        if(digits.length() == 1){
            return m.get(digits.charAt(0));
        }
        List<String> intermediate = dfs(digits.substring(1, digits.length()),m);
        for(String first : m.get(Character.toString(digits.charAt(0)))){
            for(String rest : intermediate){           // line1
                result.add(first + rest);
                }
            }
        return result;
    }

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String digits="123";
    Map<String,List<String>> selected=new HashMap<>();
    selected.put("1", new ArrayList<>(Arrays.asList("4","2","3")));
    selected.put("2", new ArrayList<>(Arrays.asList("1","2","3")));
    selected.put("3", new ArrayList<>(Arrays.asList("1","2")));
    dfs(digits,selected);
}
公共静态列表dfs(字符串数字,映射m){
列表结果=新建ArrayList();
if(digits.length()==0){
返回结果;
}
if(digits.length()==1){
返回m.get(数字字符(0));
}
List intermediate=dfs(digits.substring(1,digits.length()),m);
for(字符串开头:m.get(Character.toString(digits.charAt(0))){
对于(字符串剩余:中间){//line1
结果。添加(第一个+其余);
}
}
返回结果;
}
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
字符串数字=“123”;
Map selected=新建HashMap();
选择.put(“1”,新的ArrayList(Arrays.asList(“4”,“2”,“3”)));
selected.put(“2”,新的ArrayList(Arrays.asList(“1”,“2”,“3”)));
选择.put(“3”,新的ArrayList(Arrays.asList(“1”,“2”));
dfs(数字,选定);
}

我想问题出在这里:

return m.get(digits.charAt(0));
它应该返回
null
,因为
数字。字符(0)
不是
字符串


您需要使用
子字符串
Character.toString(
此处提取数字

发布堆栈跟踪。我没有使用堆栈,我使用递归。@我的意思是我可以使用堆栈,但我想找到上面的错误。@elhefein简单的术语;发布执行代码后得到的nullpointerException块。即使没有堆栈跟踪:D,但说真的,你需要熟悉堆栈跟踪和调试器,它将帮助您查找bug和errors@KKKK这正是我在你的另一个问题中所说的