简体   繁体   中英

Check if a Row exists in a 2D array in Java

I am having trouble fixing my code so that I stop getting

java.lang.ArrayIndexOutOfBoundsException: 6

Here is my current code:

    public static boolean isRow(int row, double[][] array)
    {
    boolean flag = false;

    if ( array != null && array.length >= 0 )
    {
        if ( array[row] != null )
        {
            flag = true;
        }
    }
    return flag;
    }

I know that I will probably have to have a for loop somewhere so that it can check to see that

!(row > array.length);

But I am just not sure how to write that in. I am using a JUNIT test that is trying to pass "6" in as the row variable.

Any help is greatly appreciated!

You need to check that row is in range for the array:

public static boolean isRow(int row, double[][] array)
{
    boolean flag = false;

    if (array != null && row >= 0 && row < array.length)
    {
        if ( array[row] != null )
        {
            flag = true;
        }
    }
    return flag;
}

or, more concisely (taking advantage of the short-circuit nature of the && operator):

public static boolean isRow(int row, double[][] array)
{
    return array != null && row >= 0 && row < array.length && array[row] != null;
}

Check if array[row] exists before requesting it in you if test.

public static boolean isRow(int row, double[][] array)
{
boolean flag = false;

if ( array != null && array.length >= 0 && array.length > row)
{
    if ( array[row] != null )
    {
        flag = true;
    }
}
return flag;
}

If I understand it correctly, all you need to check is that the row with the given index is available in the array. For which, as you wrote:

!(row >= array.length);

is enough. If the array has 6 elements, array.length will return 6. If the row index being passed is anything less than 6, it is a valid row (obv row has to be >= 0).

Edit: please notice the change in the condition to do >=, as suggested by Ted. Instead, you can simply put row < array.length. Also, null checks as per Ted's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM