2013-12-17 77 views
2

好吧,所以我告訴有一個輕微的邏輯錯誤與我的內循環。顯然如果我的[2] [2]數組是2X3元素或3X2元素,它不會工作有人可以告訴我如何解決這個小問題?邏輯錯誤與循環陣列

public static void dispArr(String [][] country){ 
    for(int i= 0; i<country.length; i++){ // both for loops count from 0 to 1 which are the only numbers required for this given array 
     for(int j= 0; j<country.length; j++){ 
      System.out.print(country[i][j]); //this will output [0][0],[0][1],[1][0] and[1][1] as identified above. 
     } 

     System.out.println("\n"); //create space between both 
    } 
} 
+0

在內部循環中試試'country [i] .length' –

+0

非常感謝大家! – user3111329

回答

8

將其更改爲:

for (int i = 0; i < country.length; i++) { 

        // note the change here 
    for (int j = 0; j < country[i].length; j++) { 
     // ... 
    } 
} 

否則,內環將不算達一樣,因爲它需要。

舉個簡單的例子,如果你有這樣的:

[[1, 2, 3], [4, 5, 6]] 

它將成爲(與你的原碼):

for (int i = 0; i < 2; i++) { 

       // oh no! not counting far enough 
    for (int j = 0; j < 2; j++) { 
     // ... 
    } 
} 

你必須採取內部數組的長度你如果對您有任何意義,請重複循環,而不是內部陣列的數量

0

country.length只給你第一個維度。 country[i].length會給你第二個維度。

+0

'country.length [i]'???咦??? – Doorknob

+0

愚蠢的拼寫錯誤 – Dom

0

在矩陣中的第一個維度您的內部循環迭代,並且可能應該

for (int j=0; j < country[i].length; j++) { ... 

代替。請注意0​​之後的[i]

乾杯,

2

在Java中,二維數組本質上是一個數組數組。因此需要在計算第二維時放置第一維(數組)的索引。

public static void dispArr(String [][] country){ 
    for(int i= 0; i<country.length; i++){ // both for loops count from 0 to 1 which are the only numbers required for this given array 

     for(int j= 0; j<country[i].length; j++){ 

      System.out.print(country[i][j]); //this will output [0][0],[0][1],[1][0] and[1][1] as identified above. 
     } 

     System.out.println("\n"); //create space between both 
    } 
}