Reputation: 15
Hello when I'm trying to run this code I'm getting following error I understand this happens when there is no main function, however I do have a main fuction..
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at FilterAs.main(FilterAs.java:21)
Here's my code
import java.io.*;
public class FilterAs {
public static int numberOfFiles(File directory) {
if (directory.isFile())
return(1);
else {
File[] list = directory.listFiles();
int count = 0;
if (list != null)
for (File file : list)
count += (file.isFile()) ? 1 : numberOfFiles(file);
return(count);
}
}
public static void main(String[] args) {
System.out.println(numberOfFiles(new File(args[0])));
}
}
Upvotes: 0
Views: 60
Reputation: 19
I guess you forgot to set arguments for your program?
You are accesing the arguments when calling the method (numberOfFiles).
Upvotes: 1
Reputation: 61158
You have a call to:
args[0]
But args
is empty.
You have called your program with something like:
java -jar MyJar.jar
But you should have called it with:
java -jar MyJar.jar /a/path/to/some/directory
i.e. you need to pass an argument to your application.
Upvotes: 0
Reputation: 393866
If there are no command line arguments passed to the program, the following would throw ArrayIndexOutOfBoundsException
since the args
array would be empty.
System.out.println(numberOfFiles(new File(args[0])));
You should check for the existence of such arguments before accessing the args
array :
if (args.length > 0) {
System.out.println(numberOfFiles(new File(args[0])));
} else {
System.out.println("Please supply a file name");
}
Upvotes: 0