1

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?

Darin Xie
  • 13
  • 2

1 Answers1

0

++tab does two things:

  • evaluates to the value of "1 more than 'the value of tab'"
  • changes the value of tab to the above value

(It actually does a lot more things, but for the purpose of understanding the code in the question, just those two is enough)

tab + 1 does one thing:

  • evaluates to the value of "1 more than 'the value of tab'"

tab + 1 does not change the value of tab.

This is crucial, because you do not want tab to change within each recursive call. Every iteration of the for (File file1 : files) loop should use the same tab, because each iteration prints out a file/directory in the same directory. It is only when you call the seekFile, that you will use a higher tab number.

If you use ++tab, and you encounter a directory, tab will be incremented, and every sibling file/directory after that will have more indentation than it should.

If you use tab + 1, The tab for the current call doesn't change.

In both cases, the value of "1 more than 'the value of tab'" is passed to the next recursive call of seekFile, and a new stack frame is created and pushed onto the call stack. Each stack frame has its own tab variable, which is why passing tab + 1 to the new call doesn't affect the tab variable in the current call.

Sweeper
  • 213,210
  • 22
  • 193
  • 313