• Post Reply Bookmark Topic Watch Topic
  • New Topic

increment counter by recursion  RSS feed

 
Juna Burk
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello to everyone,

I have a question related to the code below, that I do not understand. The aim ist to count all files and subdirectories in an ArrayList full of files and subdirectories. So I have to count every file and every subdirectory.
The code concerning counting files is clear to me - every time d is of the type file I have to increment n by one. However I thought that I have to do the same thing in case d is a directory, so I would have written the same code for directories.
So what does "n += ((Directory) d).countAllFiles();" mean? In my understanding the method countAllFiles() is applied again on the object Directory ( as Directory is the class that contains this method), but how is n incremented by this? I thought n should be incremented by one as we did with files. I would be very happy if somebody can help me :-)



Best,
Juna :-)
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Juna Burk wrote:
The code concerning counting files is clear to me - every time d is of the type file I have to increment n by one. However I thought that I have to do the same thing in case d is a directory, so I would have written the same code for directories.
So what does "n += ((Directory) d).countAllFiles();" mean? In my understanding the method countAllFiles() is applied again on the object Directory ( as Directory is the class that contains this method), but how is n incremented by this? I thought n should be incremented by one as we did with files. I would be very happy if somebody can help me :-)


Remember that "n" is a local variable. So, the recursive call has its own copy, which starts at zero, and is incremented as files are found. Incrementing the recursive call copy has no effect on the caller's copy of the variable.

This is what that line does. It increments (technically adding) the "n" variable with the count that was returned from the recursive call.

Henry
 
Juna Burk
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Henry,

thanks a lot, now everything is crystal clear to me! :-)

Best,
Juna :-)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!