简体   繁体   中英

What does the error: incompatible types: Matrix cannot be converted to int[][] mean?

I am working on a project and keep getting this error message: incompatible types: Matrix cannot be converted to int[][]...I'm still really new to java and have no clue what I have to do in order to fix this...

The errors are in lines 20 (when I return temp) line 40 (when I return scMatr) and in line 50 (when I retrun addMatr).

public Matrix transpose()
{
  //store matrix vals in variable to use as reference 
  int [][] matr = this.getMatrixVals();
  
  //create temporary int matrix
  int [][] temp;
  
  //use nested for loop to assign each of the ints
  for (int i = 0; i < matr[0].length; i++)
  {
     for (int j = 0; j < matr.length; j++)
     {
        //assign the transposed position
        temp[i][j] = matr[j][i];
     }
  }
  
  //return the temp matrix
  return temp;   
}

//method to scalar multiply 
public Matrix scalarMult(int scVal)
{
  //store matrix vals in variable to use as reference 
  int [][] matr = this.getMatrixVals();
  
  //store result of scarlar multiplication 
  int [][] scmatr;
  
   //multiplies all elements of the this object by the scVal (int) value of the parameter
   for(int i = 0; i < matr.length; i++)
   {
      for(int j = 0; j < matr[0].length; j++)
      {
         scmatr[i][j] = scVal * matr[i][j];
      }
   }
  
   //returns the resulting matrix 
   return scmatr;
}

 //method that adds the this object and the parameter Matrix object
 public Matrix add(Matrix m2)
 {
  //matrix to return with values added
  int[][] addMatr;
  
   //returns the Matrix object
   return addMatr;
}

Any help is greatly appreciated!! Thank you in advance!

The return type of all the methods (indicated by the second word in the method's declaration (the word/className that comes after the keyword public )) is a Matrix meaning that all the methods can only return a Matrix object.

All the methods in your code return 2D arrays, which are instances of the Array java class not the Matrix class.Since an array is not a Matrix, you cannot return an array, which is why you get the incompatible type error.

To fix it, you should either change the return type of the methods to be 2D array, or you should convert the array you want to return to a Matrix object and then return that Matrix object.

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