Вопрос

I was trying to do a sorting class of matrices entries and I first put them into an array

 double[][] A ={{0,70,9},{1,3,4}};

    double[] vektori_per_sortim=new double[A.length*A[0].length];

    int k=0;

    for(int i=0; i!=A.length; i++)
    {
        for(int j=0; j!=A[0].length; j++)
        {
            vektori_per_sortim[k]=A[i][j];
            k++;
        }

    }

and then I tried to put them into the matrices again

int r=0;
  while(r!=vektori_per_sortim.length)
{
    for(int i=0; i!=vektori_per_sortim.length/A.length; i++)
     {
       for(int j=0; j!=vektori_per_sortim.length/A[0].length; j++)
       {
          A[i][j]=vektori_per_sortim[r];
          r++; 

        }

      }


}

but I get an error java.lang.ArrayIndexOutOfBoundsException: 2

Can you please help me out with this?

Thank you very much.

Это было полезно?

Решение

The problem is that you mixed up your dimensions, and tried to copy the 6 element vector into a 3x2 matrix rather than a 2x3 matrix.

You can tell because when you copy the values out of the matrix, i goes from 0 to A.length. When you copy them back in, i goes from 0 to A[0].length (= vektori_per_sortim.length/A.length).

You could switch the i and j conditions, but it would be way cleaner to simply use your first loops and reverse the copy inside them:

k=0;
for(int i=0; i!=A.length; i++)
{
    for(int j=0; j!=A[0].length; j++)
    {
        A[i][j] = vektori_per_sortim[k];
        k++;
    }

}

Другие советы

You may want a different approach to putting the values back into the matrix. I would recommend iterating through the elements in the same way that you did to put them into the array, but copying them the other way this time. Try replacing the second code block with this:

int r = 0;
for(int i=0; i!=A.length; i++)
{
    for(int j=0; j!=A[0].length; j++)
    {
        A[i][j] = vektori_per_sortim[r];
        r++;
    }

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top