Home > Mobile >  Proper spacing while printing in for loop
Proper spacing while printing in for loop

Time:09-14

I am working on a program that shows all folders and sub folders in proper format but i am not able to maintain proper spacing between them



public void listf(String directoryName) {

    File directory = new File(directoryName);

    File[] fList = directory.listFiles();
    for (File file : fList) {
        if (file.isDirectory()) {
            for (File file1 : fList) {
                System.out.print("\t");
            }
          System.out.println(file.getName());
          listf(file.getAbsolutePath());
          
    }
}
}

CodePudding user response:

Here is my solution to that problem:

public void listf(String directoryName){
    recursiveListf(directoryName,2,0);
}

public void recursiveListf(String directoryName, int depth, int tabs) {
    if(depth<=0){
        return;
    }
    if(tabs<0){
        return;
    }
    File directory = new File(directoryName);

    File[] fList = directory.listFiles();
    for (File file : fList) {
        if (file.isDirectory()) {
            recursiveListf(directoryName "/" file.getName(), depth-1, tabs 1);
        }else{
            for(int i = 0; i < tabs; i  ){
                System.out.print("\t");
            }
            System.out.println(file.getAbsolutePath());
        }
    }
}

The depth describes how deep you want your folder structure to be displayed.

CodePudding user response:

If by this you mean to say you want indentation that indicates folder depth, then it's a recursive problem, with each call to itself adding another space.

A good video on understanding recursive problems

  • Related