user3068177
user3068177

Reputation: 357

Array Index Issue In Java

I am working on a program to implement Kruskal's algorithm on a minimum spanning tree. I have this as my main method inside my Kruskal.java file.

public static void main(String[] args) {
  In in;
  in = new In(args[0]);
  EdgeWeightedGraph G = new EdgeWeightedGraph(in);
  Kruskal mst = new Kruskal(G);
  for (Edge e : mst.edges()) {
        StdOut.println(e);
   }
    StdOut.printf("%.5f\n", mst.weight());
}

The problem I am having is when I try to run the program, I receive an array out of bounds exception. The exception originates from the

in = new In(args[0]);

line. I know that an array out of bounds exception occurs when, in simplified terms, when the program tries to load more items into the array than it has space for. This ultimately causes it to go "out of bounds". In the main method below, EdgeWeightGraph references another class in the program, EdgeWeightGraph.java. I believe it is being populated from the EdgeWeightedGraph class but I am not entirely sure. Any advice on how to fix this array out of bounds exception?

EDIT: Here is a link to the In.java file that I am using: http://algs4.cs.princeton.edu/12oop/In.java.html and here is my Kruskal class that the code from above comes from http://algs4.cs.princeton.edu/43mst/KruskalMST.java.html

Upvotes: 0

Views: 113

Answers (1)

Balwinder Singh
Balwinder Singh

Reputation: 2282

The error is simply occuring cause you are not passing any argument while running the main method of the given class.

So when the jre runs the following statement

in = new In(args[0]);

It doesn't get any passed arguments in the args array at 0th position; which results in this error.

Pass the argument and you won't have this error anymore.

To learn about how to correctly pass arguments to main method, refer the java documentation.

Upvotes: 2

Related Questions