Okay let's take a real problem: You want to write a file listing function. This means you have to recursively run through all directories and subdirectories.
The first question you ask yourself is: What do I need? -> Files. Next: How do I interact with files? -> File Class
Take this small piece of code
public class Listing{
//fields
private File file; //You declared a File with name file
//constructor
public Listing(){
this.file = new File("C:/text.txt");
}
public String toString(){
System.out.println(this.file.getName());
}
}
Now you got one file you can talk to. So say we want to get all the files in a directory now:
public class Listing{
//fields
private File file; //You declared a File with name file
private File folder; //A folder is also a file
//constructor
public Listing(){
this.folder = new File("C:/test);
}
public void getFiles(){
if(folder.isDirectory()){
File[] files = folder.listFiles(); //put all the files in an array
//Now what you have to do is iterate through the list till you reach the end.
/* Important to note is that arrays, collections, etc. all have one thing in common...
They have a size. It's important to know the size, because this will be the max of your loop (for now)
*/
//You can use whatever kind of loop you which, I'm going to use a for loop because it's the shortest
for(int i=0; i<files.length(); i++){
//important to note is that arrays have lengths, but if I were to work with a collection it would be a size.
System.out.println(files[i].getName());
}
//Such a loop is still too consuming, that's why most people use a for-each loop when iterating through lists to show their contents. NEVER USE A FOR EACH LOOP TO CHANGE THE VALUE OF AN OBJECT... It's just not good programming manners
for(File f:files){
System.out.println(f.getName()); //As you can see much less code
}
}
}
public String toString(){
System.out.println(this.file.getName());
}
}
Now this is a basic concept: When you want to create loops you have to think: What do I want to loop through? Objects? Numbers? Do I want to stop at a certain point? (If statement in your loop) Do I want to read or write/alter data? (for-each or for/while/do while)
Note: this is pseudo code, it might give an error or two I don't know, I just came up with it on the spot
I'm sparing real recursion because it's somewhat more advanced, but this is the basic one folder search