I'm trying to use recursion to search for all the files and their sub-files in a folder. But I want to add indentation to make the output more beautiful. I added an int variable to the variable of the function to indicate how many indents are needed.This is the final code for success.
public void seekFile(File file, int tab) {
File [] files=file.listFiles();
assert files != null;
for (File file1 : files) {
if (file1.isFile()){
for(int i = 0; i< tab; i++)
System.out.print("|\t");
System.out.println(file1.getName());
}else {
for(int i = 0; i< tab; i++)
System.out.print("|\t");
System.out.println(file1.getName());
int index = tab+1;
seekFile(file1,index);
}
}
}
At first, I used seekFile(file1, ++tab)
to do a recursion, but the indentation I got was all wrong, and the output was accurate after I swapped out the tab
. Why is that?