Java:如何移动多维数组的内容?

时间:2013-10-23 04:55:48

标签: java arrays

我目前正在开展一个小项目。我正在为L游戏编写一个简单的java程序。我需要编写一个方法来移动4x4数组的内容。此方法将采用(row, column)参数。内容将相应移动。

{ 'x',' ',' ',' ' }, 

{ 'x',' ',' ',' ' },

{ 'x','x',' ',' ' },

{ ' ',' ',' ',' ' }

移动(0,2) --->

{ ' ',' ','x',' ' },

{ ' ',' ','x',' ' },

{ ' ',' ','x','x' },

{ ' ',' ',' ',' ' }

我不知道从哪里开始。我非常感谢对此给予的任何帮助。 非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

你的方法看起来应该是这样的

char[][] array = new char[4][4];

public static void move(row, column){
    for (int i = 0, i < 4; i++) {
        for (int j = 0; j < 4; j++){
            if (array[i][j] != null) {
                // add rows and column accordingly
                array[i + row][j + column] = array[i][j];
                array[i][j] = null;
            }
        }
    }
}

这是考虑每行只有一个x,在你的情况下,有些行有两行。我会让你想出那个。

答案 1 :(得分:1)

    int moverow = 0;
    int moveCol = 2;

    for(int i = 0; i <=3; i++){
        for(int j = 0; j <=3; j++){
            int currentValue = board[i][j];
            //shifting value
            int shiftX = i + moverow;
            int shiftY = j + moveCol;
            // discarding the value if index overflows
            if(shiftX > 3 || shiftY > 3){

                // setting initial value on the original index.
                board[i][j] = 0;
                break;
            }else{
                board[shiftX][shiftY] = currentValue;
                // setting initial value on the original index.
                board[i][j] = 0;
            }
        }
    }