在我的循环中找不到ArrayIndexOutOfBoundsException:5

问题描述 投票:-3回答:3

所以我试图解决名人问题。你有一个2d数组填充0和1.行(=人)只包含1,是名人。如果没有则int n为0,并且将是行仅包含1的2d数组的列号。

问题是,我找不到ArrayIndexOutOfBoundsException。它必须在循环中的任何地方。我使用了一个5x5 2d阵列并开始使用i = 0。循环只能运行到i : 3然后抛出异常。

public int startSearch(int[][] matrix , int i) {
    int j = 0;
    int n = 0;
    int esc = 0;

    while(esc == 0) {
        if(matrix[i][j] == 1) {
            j++;

            if( j >= (matrix.length +1) ) {
                n = i+1;
                esc = 1;
            }
        }

        if(matrix[i][j] == 0) {
            esc = 1;
        }
    }

    i++;
    if( i <= matrix.length) {
        System.out.println("i : " +i);
        System.out.println(n);
        startSearch(matrix, i);
    }
    return n;
}
java arrays multidimensional-array
3个回答
0
投票

你必须注意,在Java中,数组的索引从0到长度为1,所以0, 1, 2, 3, 4为你的数组大小为5。

在循环中,您正在检查:

if( j >= (matrix.length +1) ) {
    n = i+1;
    esc = 1;
}

// and 

if( i <= matrix.length){    
    System.out.println("i : " +i);
    System.out.println(n);
    startSearch(matrix, i);
}

你应该检查:

if( j >= matrix.length ) {
    n = i+1;
    esc = 1;
}

// and 

if( i < matrix.length){    
    System.out.println("i : " +i);
    System.out.println(n);
    startSearch(matrix, i);
}

否则,例如在你的i = 3的情况下你可能有j = 5作为5 < 5+1


0
投票

在此行之前检查if(matrix[i][j] == 1)

if(i<matrix.length && j<matrix[i].length)
{
if(matrix[i][j] == 1)
{
//rest all same

还要检查此行if(matrix[i][j] == 0){之前

if(i<matrix.length && j<matrix[i].length)
{
if(matrix[i][j] == 0){
//rest all same

0
投票

可能是这一行:if(j >= (matrix.length + 1)){

当j == matrix.length + 1时,j将进入此if循环,在此之前,访问matrix[i][matrix.length]将导致ArrayIndexOutOfBoundsException,因为长度为n的数组的索引在[0,n - 1]之间,并且它是当你试图获得索引n的值时,肯定会出现错误。

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