This method must Return a result of type int[][]

Asked

Viewed 93 times

0

I’m trying to do this matrix multiplication function but it’s giving error. Shows that the error is mult(int row, int column, int Linha2, int column2, int[][] matrix, int[][] matriz2) and says 'This method must Return a result of type int[][]'

public static int[][] mult(int linha, int coluna, int linha2, int coluna2, int[][] matriz, int[][] matriz2) {
    
        if(matriz[0].length == matriz2.length){
            int[][] matrizR = new int[linha][coluna2];

            for(int i = 0; i < linha; i++){
                for(int j = 0; j < coluna2; j++)
                    for(int k = 0; k < linha2; k++)
                    matrizR[i][j] = matriz[i][k] * matriz2[k][j];
            }
        return matrizR;
        }
    }
  • 1

    What should the function return if it doesn’t enter if? null? Add a return in case it doesn’t enter the if that will work.

  • Not yet. I think it stops before you get to if, because the problem is in the function name and the variables.

1 answer

1


All paths in your code need to have a return. You have specified the return within the IF, but if you do not enter the IF function follows to the end without any return command.

There are 2 simple ways to solve this:

  1. Checks the number of rows and columns before calling the function.

  2. Keeps checking the function and returns null if multiplication is not possible.

     public static int[][] mult(int linha, int coluna, int linha2, int coluna2, int[][] matriz, int[][] matriz2) {
    
        if(matriz[0].length == matriz2.length){
            int[][] matrizR = new int[linha][coluna2];
    
            for(int i = 0; i < linha; i++){
                for(int j = 0; j < coluna2; j++)
                    for(int k = 0; k < linha2; k++)
                       matrizR[i][j] = matriz[i][k] * matriz2[k][j];
            }
            return matrizR;
         }
        else 
            return null;
     }
    

The way you are calculating the multiplication is incorrect, gives a check.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.