0

I have an exercise on Dijkstra's Algorithm and when I run my programm I get the following error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 48
What is wrong? I can't sent the entire code because it is 200 lines. But the problem appears in those lines in cmd
dist[i] = Integer.MAX_VALUE; and dist[i] = 0;

Thanks in advnace for your help.

public static void DijkstraOnNode (int start) {

  int[] dist = new int [myNodes.size()]; //where myNodes is an ArrayList of Hashset<Link>
                                         //and Link is a class that contains node kai weight       
  int[] pred = new int [myNodes.size()];  
  int[] pq = new int [myNodes.size()];

 for (int i = 0; i <= myNodes.size(); i++) {

    if (i!= start)
        dist[i] = Integer.MAX_VALUE;
    else
        dist[i] = 0;

   pq[i] = dist[i];
}

(the code continues)

MariaP
  • 27
  • 1
  • 1
  • 7
  • 4
    Arrays are 0 base indexed. So it should be `for(int i = 0; i < myNodes.size(); i++) {` – Alexis C. Apr 14 '14 at 16:38
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Alex Celeste Oct 18 '15 at 16:25

2 Answers2

3
for (int i = 0; i <= myNodes.size(); i++) 

This causes the problem change it to

for (int i = 0; i < myNodes.size(); i++) 

Because, lets say myNodes.size() returns 8 and you are trying to reach dist[8] but dist[] array starts at 0 and ends at 7.

Salih Erikci
  • 5,076
  • 12
  • 39
  • 69
  • Better yet use `dist.length` – Ingo Apr 14 '14 at 16:42
  • I did so, but when I run the programm again in cmd it returns nothnig. Either it will let me type anything. Like a non stop loop. But perhaps thats a problem in another method.. Thanks anyways! – MariaP Apr 14 '14 at 16:46
  • @MariaP your method is void and doesn't print out anything. – Salih Erikci Apr 14 '14 at 16:49
  • Well i have in the method if (printArrays) { System.out.println("Predecessor matrix"); System.out.println(Arrays.toString(pred)); and when i want to run just the algorithm printArrays is initialized as false but when I want to print them I initialize it with true. Does void not allow it? – MariaP Apr 14 '14 at 17:01
  • @MariaP it is ok then. You can print in a void method. – Salih Erikci Apr 14 '14 at 19:32
0

Arrays: numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. So in the loop:

for (int i = 0; i <= myNodes.size(); i++)

you try to access the element of the array : dist[myNodes.size()] which does not exist. It's Out Of Bounds of the array. The last element of the array has index: myNodes.size() - 1

You could see more about arrays here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Geo_Python
  • 123
  • 2
  • 9