My programming is rusty and need help to do some various methods that recursivel
ID: 3620871 • Letter: M
Question
My programming is rusty and need help to do some various methods that recursively traverse a 'psuedo file directory' listing. The files aren't real files but rather instances of a 'File' class. A folder contains a linked list full of contents which could be Folders or Files. Super class is the FSObject.Below is the code I have right now. 1. I have compile error that the return statement is not reachable. So, right now I don't even know if this code is correct as far as traversing the tree. If I get this one method correct, the others follow suit and I'm golden!
public int countFiles(FSObject fso) { if(fso instanceof File) {//fso is a File return 1; } else { //fso is a folder, parse the contents of the folder recursively LinkedList folderContents = ((Folder)fso).getContents(); for(int i=0; i<folderContents.size(); i++) { return 0+countFiles((FSObject)folderContents.get(i)); } } }
public int countFiles(FSObject fso) { if(fso instanceof File) {//fso is a File return 1; } else { //fso is a folder, parse the contents of the folder recursively LinkedList folderContents = ((Folder)fso).getContents(); for(int i=0; i<folderContents.size(); i++) { return 0+countFiles((FSObject)folderContents.get(i)); } } } public int countFiles(FSObject fso) { if(fso instanceof File) {//fso is a File return 1; } else { //fso is a folder, parse the contents of the folder recursively LinkedList folderContents = ((Folder)fso).getContents(); for(int i=0; i<folderContents.size(); i++) { return 0+countFiles((FSObject)folderContents.get(i)); } } }
Explanation / Answer
You need to use a variable to store the current count during the for-loop. You want to add the results of calling countFiles() on each file or folder in the current folder, and then return the result. The compiler error is because, as far as the compiler knows, you may never pass through the loop, in which case neither return statement would be called, and the method would end without returning. This might happen, for example, if you called this method on an empty folder. One word of caution: If folders can point to themselves, or to another folder that points to the first folder (or any other recursive way of pointing to itself), then calling this method on such a folder will cause infinite recursion. A solution would be to keep track of the folders already traversed, and to return zero if the folder being checked was traversed before.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.