Wrapping up this intro to java/programming course and recursion has hit me hard with an Inception effect.
I just can't seem to figure it out how to solve this inherently recursive assignment.The task is to check a directory path and read the files within that path; also, if there are more directories within it, we have to go deeper into those directories to read the files within them - if any.
What you're looking at is my skeleton of the assignment:
public class SearchingForStrings {
public static void main(String[] args) {
String path = "."; // Default
File sf = new File(path);
String mainDirectory = args[0]; // These two are just
String keyString = args[1]; // command-line arguments
countLinesWithString(sf, mysteriesDirectory, keyString);
}
public static int countLinesWithString(File startPath, String mainDirectory, String keyString) {
if(!startPath.exists()) {
throw new IllegalArgumentException("File " + startPath + " does not exist!");
} else if(startPath.isFile()) {
// Just to show where the file is located
// Temporary parsing to postpone an error
//TODO: Consider removing this
return Integer.parseInt(startPath.getAbsolutePath());
} else if(startPath.isDirectory()) {
// This is where our recursion would take place: essentially
// we will be going 'deeper' into the directory until we find a file
countLinesWithString(startPath, mainDirectory, keyString);
} else {
throw new IllegalStateException("Unknown file type: " + startPath);
}
}
}
Could someone explain this; feel free to ask for more information if needed
P.S. I've read just about every Oracle database/tutorial on recursion (They aren't helping).
This post has been edited by Invoker: 01 November 2014 - 08:44 PM

New Topic/Question
Reply


MultiQuote




|