gpt4 book ai didi

java - 递归必须解析为类型,但我不知道如何构造它?

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

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 be while (path.length >1) ,但随后它就进入无限循环..有人可以帮助我使用替代结构吗?

最佳答案

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

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 主体中。

关于java - 递归必须解析为类型,但我不知道如何构造它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917907/

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