Reputation: 25
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!
Upvotes: 0
Views: 5517
Reputation: 429
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.
Upvotes: 0
Reputation: 602
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;
}
Upvotes: 1
Reputation: 234857
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;
}
Upvotes: 2