为什么我在这个特定的代码中得到ArrayIndexOutOfBoundsException



我在Dijkstras算法中有类似的东西,但我没有出错。我试过用不同的值来代替整数max和其他各种各样的东西,但都不起作用。我也搜索过这个网站和其他网站,但没有找到任何帮助。另外,如果它有区别的话,我的图类本身就是一个类。如有任何帮助,我们将不胜感激。我更新了我的问题。。。问题得到了回答。但我确实重新格式化了,以防其他人想看一看。

public static void main(String[] args)
{
final static int V=7;
static final int E=13;
Graph graph=new Graph(V,E);
graph.edge[0].src = 1; 
graph.edge[0].dest = 2; 
graph.edge[0].weight = 5; 
graph.edge[1].src = 1; 
graph.edge[1].dest = 3; 
graph.edge[1].weight = 8; 
graph.edge[2].src = 1; 
graph.edge[2].dest = 5; 
graph.edge[2].weight = 7; 
graph.edge[3].src = 1; 
graph.edge[3].dest = 6; 
graph.edge[3].weight = 10; 
graph.edge[4].src = 2; 
graph.edge[4].dest = 3; 
graph.edge[4].weight = -2; 
graph.edge[5].src = 2; 
graph.edge[5].dest = 5; 
graph.edge[5].weight = -2; 
graph.edge[6].src = 3; 
graph.edge[6].dest = 4; 
graph.edge[6].weight = 6; 
graph.edge[7].src = 5; 
graph.edge[7].dest = 4; 
graph.edge[7].weight = 4; 
graph.edge[8].src = 5; 
graph.edge[8].dest = 6; 
graph.edge[8].weight = 2;
graph.edge[9].src = 5; 
graph.edge[9].dest = 7; 
graph.edge[9].weight = 7;
graph.edge[10].src = 6; 
graph.edge[10].dest = 7; 
graph.edge[10].weight= -1; 
graph.edge[11].src = 7; 
graph.edge[11].dest = 3; 
graph.edge[11].weight = 4;
graph.edge[12].src = 7; 
graph.edge[12].dest = 4; 
graph.edge[12].weight = 5;


Graph.BellmanFord(graph,0);
}

public class Graph 
{

public class Edge { 
int src, dest, weight; 
Edge() { 
src = dest = weight = 0; 
} 
}; 
int V, E; 
Edge edge[]; 
Graph(int v, int e) 
{ 
V = v; 
E = e; 
edge = new Edge[e]; 
for (int i=0; i<e; ++i) 
edge[i] = new Edge(); 
}

static void bellmanford(Graph graph , int src )
{
int V = graph.V, E = graph.E; 
int dist[]=new int[V];
for (int i=0; i<V; ++i) 
dist[i] = Integer.MAX_VALUE; 
dist[src] = 0; 

for (int i=1; i<V; ++i) 
{ 
for (int j=0; j<E; ++j) 
{ 
int u = graph.edge[j].src; 
int v = graph.edge[j].dest; 
int weight = graph.edge[j].weight; 
if (dist[u]!=Integer.MAX_VALUE && // I’m getting the error        
here.
dist[u]+weight<dist[v]) 
dist[v]=dist[u]+weight; 
} 
} 
for (int j=0; j<E; ++j) 
{ 
int u = graph.edge[j].src; 
int v = graph.edge[j].dest; 
int weight = graph.edge[j].weight; 
if (dist[u]!= Integer.MAX_VALUE && 
dist[u]+weight < dist[v]) 
System.out.println("Graph contains negative weight cycle"); 

}
printdistb(dist,V);
}

static void printdistb(int dist[], int V) 
{ 
System.out.println("Vertex   Distance from Source"); 
for (int i = 0; i< V; ++i) 
System.out.println(i+"            "+dist[i]); 
} 

您正在声明长度为V的数组dist[]。然后使用graph.edge[j].src作为dist[]数组的索引。这就是您获得ArrayIndexOutOfBoundsException的原因。简而言之,这意味着src值大于V.

修复

dist[]的长度增加1。

static void bellmanford(){...}内部的变化

int dist[] = new int[V];

int dist[] = new int[V+1];

这确实解决了我的异常问题。但算法似乎有更多的逻辑问题(实际问题可能隐藏在其他地方更深。(。但至少程序现在正在执行,所以你可以调试它。祝你好运。

相关内容

  • 没有找到相关文章

最新更新