Adam
Adam

Reputation: 2398

Java Finding Min amongst 2-D array

I get an out of bounds error for the line: int currentInt = matrix[i][j];

public class Matrix
{
    private int[][] matrix;

    /**
     * Constructor for objects of class Matrix
     * @param array a 2-d array
     */
    public Matrix(int[][] array)
    {
       matrix = array;
    }

    public int min()
    {
       int min = matrix[0][0];
        for(int i = 0; i < matrix.length; i++)
        {
            for(int j = 0; i < matrix[0].length; i++)
            {
                int currentInt = matrix[i][j];
                if(min > currentInt)
                {
                   min = currentInt;
                }


            }
        }
        return min;
    }

}

Upvotes: 0

Views: 43

Answers (3)

Change

for(int j = 0; i < matrix[0].length; i++)

to

for(int j = 0; j < matrix[i].length; j++)

Upvotes: 1

JNL
JNL

Reputation: 4703

You forgot to change the j in the 2nd for loop

for(int j = 0; i < matrix[0].length; i++)

should be

for(int j = 0; j < matrix[0].length; j++)

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93842

for(int j = 0; i < matrix[0].length; i++)

should be

for(int j = 0; j < matrix[i].length; j++)

or if the array is square :

for(int j = 0; j < matrix[0].length; j++)

Upvotes: 2

Related Questions