递归必须解决键入但我不知道如何构造它?

时间:2014-07-23 18:14:06

标签: java if-statement recursion while-loop

public static Directory makePath(Directory parent, String[] path) {
    // While path has more than one item in it, recurse
    if (path.length > 1) {
        System.out.println(parent + "1");
        // If dir exists, go into the next level
        if (parent.isChildDirectory(path[0])) {
            String[] newPath = Arrays.copyOfRange(path, 1, path.length);
            Directory newParent = parent.getChildDirectory(path[0]);
            FileSystem.makePath(newParent, newPath);
        }
        // If dir does not exist, create it and then go into the next level
        else {
            parent.addDirectory(path[0]);
            String[] newPath = Arrays.copyOfRange(path, 1, path.length);
            Directory newParent = parent.getChildDirectory(path[0]);
            FileSystem.makePath(newParent, newPath);
        }
    } else {
        System.out.println(parent + "2");
        // If dir exists, go into the next level
        if (parent.isChildDirectory(path[0])) {
            return parent.getChildDirectory(path[0]);
        }
        // If dir does not exist, create it and then go into the next level
        else {
            parent.addDirectory(path[0]);
            return parent.getChildDirectory(path[0]);
        }
    }
}

Java现在不会编译此方法,因为在第一个if部分中,结果不会返回Directory对象。 之前我有if / else是while(path.length> 1),但是它只是进入无限循环。有人可以帮助我使用另一种结构吗?

1 个答案:

答案 0 :(得分:2)

怀疑你只想返回递归调用的结果。所以转过这些电话:

FileSystem.makePath(newParent, newPath);

return FileSystem.makePath(newParent, newPath);

虽然我认为值得注意的是你在这里有很多重复的代码 - 所以这个:

if (parent.isChildDirectory(path[0])) {
    String[] newPath = Arrays.copyOfRange(path, 1, path.length);
    Directory newParent = parent.getChildDirectory(path[0]);
    return FileSystem.makePath(newParent, newPath);
}
// If dir does not exist, create it and then go into the next level
else {
    parent.addDirectory(path[0]);
    String[] newPath = Arrays.copyOfRange(path, 1, path.length);
    Directory newParent = parent.getChildDirectory(path[0]);
    return FileSystem.makePath(newParent, newPath);
}

可能只是:

if (!parent.isChildDirectory(path[0])) {
    parent.addDirectory(path[0]);
}
String[] newPath = Arrays.copyOfRange(path, 1, path.length);
Directory newParent = parent.getChildDirectory(path[0]);
return FileSystem.makePath(newParent, newPath);

尝试隔离只是有条件的行为,并且仅在if正文中包含该行为。