索引超出范围,为什么?

问题描述 投票:0回答:1
public int checkAdj(@NotNull int[] fit) {
    int count=0;
    int vertex =1;

        for (int i = 0; i < fit.length - 1; i++)
            if (adjacencyList[fit[i]][fit[vertex]] != 0) {
                count++;
                vertex++;

            }

    if(adjacencyList[fit.length-1][fit[0]]==1) {
        count++;
    }
    return count;
}

我在我的项目中具有此功能。这是一个相当大的项目,因此我将尝试使其保持在该功能的重点。它获取一个顶点数组,并搜索该数组和一个表示邻接矩阵的2d数组。我只是在寻找有多少个顶点彼此相邻并返回该数字。对于大小为5和18的数组,代码可以正常工作(有时会低计数和高计数),但是当数组的大小为13时,我得到了超出界限的异常的索引,我也不知道为什么。

java arrays indexoutofboundsexception
1个回答
0
投票

问题可能出在这两个地方:

if (adjacencyList[fit[i]][fit[vertex]] != 0) {
   count++;
   vertex++;
}

如果adjacencyList的大小为5 * 5,并且fit [i]为10,它将超出范围。另外,在

if(adjacencyList[fit.length-1][fit[0]]==1) {
    count++;
}

如果adjacencyList为5 * 5,并且fit.length - 1为9,则索引超出范围。

请帮忙投票。

© www.soinside.com 2019 - 2024. All rights reserved.