Search code examples
javaarraysmultidimensional-arraycharacter-arrays

Java switching char elements in a 2d array


I'm trying to switch two elements in a 2d char array, and it's not working. I've read in other similar questions to this that the temp variable should be a 1d array, but I'm not convinced that's true. Can anyone help me understand why this isn't working?

public static void moveTo(char[][] tissue, int i, int j){
    char temp = tissue[i][j];

    for(int k = 0; k < tissue.length; k++){
        for(int l=0; l<tissue.length; l++){
            if(tissue[k][l] == ' '){
                tissue[k][l] = tissue[i][j];
                tissue[k][l] = temp;
                return;
            }
        }
    }
}

Solution

  • In the second loop, you have to use tissue[k].length.

    And tissue[i][j] must be affected with the blank character (if i am understanding well). temp is useless.

    public static void moveTo(char[][] tissue, int i, int j){    
        for(int k = 0; k < tissue.length; k++){
            for(int l=0; l<tissue[k].length; l++){
                if(tissue[k][l] == ' '){
                    tissue[k][l] = tissue[i][j];
                    tissue[i][j] = ' ';
                    return;
                }
            }
        }
    }