char数组的值不断变化

时间:2014-02-21 16:24:59

标签: java class object multidimensional-array global-variables

我有两个不同的二维数组,用于存储表格中的地图:

 [#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]
 [#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #]
 [#, ., ., ., ., ., ., 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的值都是:

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

任何人都可以告知为什么会这样。

非常感谢:)

1 个答案:

答案 0 :(得分:2)

您实际上是将TwoDArray变量的引用(的值)传递给createBlankArray方法。既然你有:

mapArrayGlobal = TwoDArray;
mapBlank = mapArrayGlobal;

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

顺便说一句,您不应该使用大写字母来启动变量/实例名称。命名变量的约定是camelCase