简体   繁体   English

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

[英]Java: how to move the contents of a multidimentional array?

I'm currently working on a small project. 我目前正在做一个小项目。 I'm writing a simple java program for the L game. 我正在为L游戏编写一个简单的Java程序。 I need to write a method that will move the content of a 4x4 array. 我需要编写一个方法来移动4x4数组的内容。 This method will take in (row, column) parameters. 该方法将接受(row, column)参数。 and the contents will move accordingly. 内容将随之移动。

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

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

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

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

move (0, 2) ---> 移动(0,2)--->

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

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

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

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

I'm not sure where to start. 我不确定从哪里开始。 I really appreciate any help given on this. 我真的很感谢在此方面提供的任何帮助。 Thank you so much for your help. 非常感谢你的帮助。

your method should look something like this 您的方法应如下所示

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;
            }
        }
    }
}

This is considering there is only one x per line, which in your case, some lines have two. 这是考虑到每行只有一个x ,在您的情况下,有些行有两个。 I'll let you figure that one out. 我让你想一想。

    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;
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM