为什么我写的代码中有一个索引超出了边界?

如题所述

索引超出了数组界限解决方法:

a.connected[i] = vertices[i+1];

称之为索引i+1。这将导致一个index out of bounds exception。(在你n等于19的例子中:有效索引将是[0-18]。

你的循环将从0-18开始,但是在该行中,它将会添加一个18 + 1 = 19,这是一个无效索引)在你的循环中将条件更改为:

for (int i = 0; i<n-1; i+=2){

确保它在添加之后不会超出界限。

Vertex [] vertices = new Vertex[n]; int [] numbers = new int[n*2]; AdjacencyList[] all = new AdjacencyList [n+1];for (Vertex v : vertices){
System.out.println(v.value);

AdjacencyList a = new AdjacencyList(v);
for (int i = 0; i < n; i += 2)
{

if (numbers[i] == v.value){
a.connected[i] = vertices[i+1];//array index out of bounds exception:19
else { a.connected[i] = v; }
}
all[0] = a; //add the finished adjacency list to the array

}

与n = 19我可以得到一个索引超出边界错误在代码中指出的点。我不确定我哪里会出问题,因为一切都还在19的范围内。

顶点=顶点列表[1-19],数字是一个平坦的边缘数组。

温馨提示:答案为网友推荐,仅供参考
相似回答