1

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)
salpenza
  • 37
  • 7
  • 1
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – seenukarthi Oct 21 '19 at 03:30

2 Answers2

1

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:

  1. You need to supply arguments. For example, if you are running the program from the command line:

      $ java name.of.your.mainclass filename
    
  2. 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);
    }
    
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks for your reply. I tried to run it from command line and received the same error. I believe that I need to add Program arguments, would this solve my problem? – salpenza Oct 21 '19 at 03:56
  • 1) If you ran the program from the command line and it gave you the same error, you forgot to include the filename argument. 2) Providing an argument solves part of the problem. The other part of the problem is that you should fix the code so that it doesn't throw an exception when the user doesn't provide arguments That's just bad programming. A bug. You should fix it. – Stephen C Oct 22 '19 at 01:10
0

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

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
EricHo
  • 183
  • 10