2014-11-22 56 views
0

我調用函數移動與2維陣列全零的點[6,5]其具有值0 。該功能將值增加到。局部變量的更新全局在Java

然後同樣的功能調用自身再次舉動(X - 1,Y,地圖,ⅰ),這就意味着它是在點[5,5]與值,它增加了到並結束本身。

但是爲什麼變量也被更新的函數,它被稱爲第一?

private static byte[10][10] myMap = {*all zeros*}; 

public static void main(String[] args) { 
    move(6, 5, myMap, 0); 
} 

private static void move(int x, int y, byte[][] map, int i) { 
    if (map[x][y] == 0) { 
     map[x][y]++; 
     i++; 
    } 
    if (i > 1) return; 

    System.out.print(x + " " + y); 
    // 6 5 
    System.out.print(map[5][5] + " " + i); 
    // 0 1 
    move(x - 1, y, map, i); 

    System.out.print(map[5][5] + " " + i); 
    // 1 1 ... WTH? Shouldn't this return 0 1 like above? 
} 

而當它更新地圖,爲什麼它不更新變量?

我掙扎小時找到原因,但仍然不知道:/ 感謝您的幫助

+0

什麼'私人靜態的byte [] [] = MYMAP新的字節[10] [10]'?請注意,在Java中,數組總是會被初始化爲「false」,「0」或「null」。 – 2014-11-22 13:43:38

+0

我已經更新了使用地圖的答案中的一些示例,但最終您可能希望創建一個使用'byte [] []'作爲字段(或稱爲'GameMap',但不是'Map',因爲這是來自'java.util'的重用類)。 – 2014-11-22 14:18:20

+0

@owlstead謝謝,我只需要cloneMap函數..因爲我沒有做任何遊戲,我不需要存儲地圖,我唯一關心的是**我**和時間多久需要考慮我正在建設的機器人旅行..我刪除了所有的方法和東西,只是爲了顯示我的問題;) – user2781994 2014-11-22 16:51:10

回答

3

這可以一見鍾情是混亂的,但它是很容易當你明白通過引用傳遞理解並通過價值傳遞。數組變量由對實際數組的引用組成。基本上他們被視爲對象相同。這意味着你正在更新你給該函數的地圖。

int變量是基本類型(intshortbytelongcharfloatdouble,當然boolean - 記下名字的首字母小寫字符),這是由值在Java中通過。基本上是價值的副本。所以你永遠不能使用這樣的變量來返回任何值。如果你想這樣做,你需要一個return聲明。


例如:

// using depth first, then width!!! 
private static byte[][] myMap = new byte[10][10]; 

public static void main(String[] args) { 
    move(6, 5, myMap, 0); 
} 

private static byte[][] cloneMap(byte[][] map) { 
    byte[][] newMap = new byte[map.length][]; 
    for (int x = 0; x < map.length; x++) { 
     newMap[x] = map[x].clone(); 
    } 
    return newMap; 
} 

private static void printMap(byte[][] map) { 
    for (int x = 0; x < map.length; x++) { 
     for (int y = 0; y < map[0].length; y++) { 
      System.out.printf("%3d ", map[x][y] & 0xFF); 
     } 
     System.out.printf("%n"); 
    } 
} 

private static int move(int x, int y, byte[][] map, int i) { 
    if (map[x][y] == 0) { 
     map[x][y]++; 
     i++; 
    } 
    if (i > 1) return i; 

    System.out.printf("x: %d, y: %d%n", x, y); 
    // 6 5 

    printMap(map); 
    System.out.printf("i: %d%n", i); 

    // -- note, you may still be missing some way of storing the maps 
    map = cloneMap(map); 
    i = move(x - 1, y, map, i); 

    // System.out.println(map[5][5] + " " + i); 
    printMap(map); 
    System.out.printf("i: %d%n", i); 
    return i; 
} 
+0

好的,謝謝!但如何通過價值傳遞數組? – user2781994 2014-11-22 13:23:19

+3

@Dev no。一切都是按價值傳遞的。 – MeBigFatGuy 2014-11-22 13:34:31

+0

@owlstead我的壞,我翻了它(公平你做了以及編輯之前,讓我絆倒)。我的觀點是,基元和對象的處理方式與按值傳遞相同,只是基元本質上是不變的。無論哪種方式+1的解釋。 – Dev 2014-11-22 13:35:51