我有两个不同的二维数组,用于以以下形式存储地图:

 [#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]
 [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #]
 [#, ., ., ., ., ., ., G, ., ., ., ., ., ., ., ., E, ., #]
 [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #]
 [#, ., ., E, ., ., ., ., ., ., ., ., ., ., ., ., ., ., #]
 [#, ., ., ., ., ., ., ., ., ., ., G, ., ., ., ., ., ., #]
 [#, ., ., ., ., ., ., ., ., ., ., ., ., ., P, ., ., ., #]
 [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #]
 [#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]


我已将其分配给变量mapArrayGlobal,但是当我调用方法createBlankArray()时,似乎会更改此变量。我对该课程的完整代码如下:

 static int Column, Row, goldNumber;
int goldCount = 0;
char [][] mapArrayGlobal, mapBlank;
boolean goldMarker = false;
boolean exitSet = false;

public void setPosition(int rows, int column, char [][] TwoDArray, int goldValue){
    goldNumber = goldValue;
    Column = randInt(1, column - 1);
    Row = randInt(1, rows - 2);

    mapArrayGlobal = TwoDArray;
    mapBlank = mapArrayGlobal;

    if(mapArrayGlobal[Row][Column] == '#'){
        setPosition(rows, column, TwoDArray, goldValue);
    }
    else if(mapArrayGlobal[Row][Column] == 'G'){
        goldMarker = true;
        mapArrayGlobal[Row][Column] = 'P';
    }
    else{
        mapArrayGlobal[Row][Column] = 'P';
    }
    createBlankArray(TwoDArray);
}

public void createBlankArray(char [][] array){
    printArray(array);
    for(int i = 1; i < array.length - 1; i++){
        for(int j = 1; j < array[0].length - 1; j++){
            mapBlank[i][j] = '?';
        }
    }
    printArray(mapBlank);
    printArray(mapArrayGlobal);
}

public static int randInt(int min, int max) {

    Random rand = new Random();

    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}


在此代码的结尾,mapArrayGlobal和mapBlank的值均为:

 [#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]
 [#, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, #]
 [#, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, #]
 [#, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, #]
 [#, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, #]
 [#, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, #]
 [#, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, #]
 [#, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, #]
 [#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]


任何人都可以建议这是为什么。

非常感谢 :)

最佳答案

实际上,您正在将TwoDArray变量的引用(值)传递给createBlankArray方法。由于您拥有:

mapArrayGlobal = TwoDArray;
mapBlank = mapArrayGlobal;


mapBlank指向mapArrayGlobal,后者指向TwoDArray,因此更改mapBlank会导致更改TwoDArray的元素。

顺便说一句,您不应以大写字母开头的变量/实例名称。变量的命名约定为camelCase

08-04 04:23