Pass data from a matrix to a vector

1

I have a problem, I have a matrix 5x5 with random numbers from 0 to 1000, I must take the odd numbers from the matrix, add them to a vector and return that vector.

This is the method that should return the vector with the odd numbers

public int[] s() {
    for(int i = 0; i<matriz.length; i++) {
        for(int j = 0; i < matriz.length; j++) {
            if(matriz[i][j] % 2 != 0) {
                vector[cont] = matriz[i][j]; 
                cont++; 
            }
        }
    }
    return vector;
}

The variable cont is initialized to 0 and the size of the vector is the multiplication of rows and columns.

But I have an exception that is the following:

  

"Exception in thread" main "java.lang.ArrayIndexOutOfBoundsException:   5 "

I guess there is an illegal index but I can not find a way to fix it.

    
asked by mb0 05.02.2018 в 05:47
source

1 answer

3

In the second for the comparison should be based on J if not the for more internal would show this exception since in the first iteration of the external for i= 0 and as in for more internal never changes the value of i the condition will always be true, but J will continue advancing until it is i =0 ; J=6 and throw the exception in matriz[i][j] . You should also get the length of the current row.

for(int i = 0; i<matriz.length; i++) {
    // remplazamos i por j , condición del for
    for(int j = 0; j < matriz[i].length; j++) {
        if(matriz[i][j] % 2 != 0) {
            vector[cont] = matriz[i][j]; 
            cont++; 
        }
    }
}
    
answered by 05.02.2018 / 07:33
source