Reputation: 37
For some reason, I am getting this error and I am very confused at this point. How can I correct this problem?
public static void main(String[] args) throws FileNotFoundException {
Memory myMemory = new Memory();
File file = new File(args[0]);
myMemory.fileParser(file);
}
This is my error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Memory.main(Memory.java:262)
Upvotes: 1
Views: 1339
Reputation: 183
Have you passed any arguments to the main method when you run the programme?
You have to explicitly pass strings to the args in main(String[] args)
, otherwise args[0]
will throw an exception
How to pass an arg in eclipse: Invoking Java main method with parameters from Eclipse
Upvotes: 0
Reputation: 719386
It is clear that you have run the program without supplying any command line arguments. As a result, the args
arraay has length zero. Your code is not designed to cope with it, and it is trying to use an argument taken from a position beyond the end of the array.
There are two parts to the solution:
You need to supply arguments. For example, if you are running the program from the command line:
$ java name.of.your.mainclass filename
You need to modify the program so that it detects that it has been called without arguments and prints an error message. For example:
public static void main(String[] args) throws FileNotFoundException {
if (args.length != 1) {
System.err.println("Filename argument missing.")
System.err.println("Usage: <command> <filename>");
System.exit(1);
}
Memory myMemory = new Memory();
File file = new File(args[0]);
myMemory.fileParser(file);
}
Upvotes: 1