简体   繁体   中英

I don't understand the program

I wanted a program which could list all the contents available in a directory. I found a nice code in java2's.com, http://www.java2s.com/Code/Java/File-Input-Output/ListingtheDirectoryContents.htm

And here is the code,

import java.io.File;
import java.util.Arrays;

public class Dir {

  static int indentLevel = -1;

  static void listPath(File path) {
    File files[]; 
    indentLevel++; 

    files = path.listFiles();

    Arrays.sort(files);
    for (int i = 0, n = files.length; i < n; i++) {
      for (int indent = 0; indent < indentLevel; indent++) {
        System.out.print("  ");
      }
      System.out.println(files[i].toString());
      if (files[i].isDirectory()) {
        listPath(files[i]);
      }
    }
    indentLevel--; 
  }

  public static void main(String args[]) {
    listPath(new File(".\\code"));
  }
}

What I don't understand is the variable n in the first for loop. If it is not defined anywhere, then why is the program not showing any error?

 int i, n;

would declare two ints.

In the code

  int i = 0, n = files.length;

declares and initialises them.

It's declared right there, as an int . The comma separates the multiple variable declarations.

n is defined in the for loop in the same way as i.

int x,y; Would define two variables x and y both as ints. the comma in the for with assignments just looks more complex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM