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 won't compile this method right now because in the first if section, the results don't return Directory objects. I had the if/else be while (path.length >1) before, but then it just goes into infinite loop.. Can someone help me with an alternative structure?
I suspect you just want to return the results of the recursive calls. So turn these calls:
FileSystem.makePath(newParent, newPath);
into
return FileSystem.makePath(newParent, newPath);
Although I think it's worth noting that you have a lot of duplicated code here - so this:
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);
}
could just be:
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);
Try to isolate just the behaviour which is conditional, and only include that in your if
body.
See more on this question at Stackoverflow