2012-10-04 144 views
0

你好,我的二維數組列打印兩次。請幫我找出錯誤的代碼。下面是我曾嘗試:Java二維數組列打印兩次

public class ArrayExercise { 
public static void main(String[] args){ 


    String[][] myArray = { 
     {"Philippines", "South Korea", "Japan", "Israel"}, // Countries 
     {"Manila", "Seoul", "Tokyo", "Jerusalem" } // capital cities 
    }; 

    String outputString = String.format("%16s\t%9s", "Country", "City"); 
    System.out.println(outputString); 

    for(int col = 0; col < myArray[0].length; ++col){ 
     for(int row = 0; row < myArray.length; ++row){ 
      System.out.printf("%16s\t%9s", myArray[0][col], myArray[1][col] ); 
     }   
     System.out.println();   
    } 
    } 

} 

它的駕駛我堅果,我似乎無法找到錯誤:(

+1

刪除內部for循環...而你剛纔問這個問題剛纔?我以爲你的疑問很清楚.. –

+0

再次感謝@RohitJain! –

回答

3

在你的內循環,要打印兩行: - myArray[0][col], myArray[1][col]

然後你迭代的那件事兩次使用內循環: -

for(int row = 0; row < myArray.length; ++row){ 
     System.out.printf("%16s\t%9s", myArray[0][col], myArray[1][col] ); 
    } 

您需要刪除此內環: -

for(int col = 0; col < myArray[0].length; ++col){ 

    System.out.printf("%16s\t%9s", myArray[0][col], myArray[1][col] ); 

    System.out.println();   
} 
1

取出內循環,因爲你有效地不需要它爲你所要完成:

for (int col = 0; col < myArray[0].length; ++col) { 
    System.out.printf("%16s\t%9s", myArray[0][col], myArray[1][col]); 
    System.out.println(); 
} 

也就是說,每個國家(myArray[0][col]),打印其省會城市(myArray[1][col]

1

內環使得打印TWI CE。你永遠不會使用row

for(int col = 0; col < myArray[0].length; ++col){ 
    System.out.printf("%16s\t%9s", myArray[0][col], myArray[1][col] ); 
    System.out.println();   
} 
+0

謝謝隊友!我沒有注意到它。 –

1

代碼循環兩次,同時打印相同的東西。刪除內循環。

0

使用本:

System.out.printf("%16s\t", myArray[row][col] ); 

代替:

System.out.printf("%16s\t%9s", myArray[0][col], myArray[1][col] ); 

要打印兩行: - myArray[0][col], myArray[1][col]

+0

有道理謝謝! –

0

你 「myArray.length」 是二。因此代碼通過內部的「for」循環兩次。循環變量「row」在內部的「for」中不會被使用。因此,同樣的事情打印兩次。

拿出內在的「for」。

1

你有一個循環太多,我刪除了最內層的一個,它按預期工作。

public static void main(String[] args){ 


    String[][] myArray = { 
     {"Philippines", "South Korea", "Japan", "Israel"}, // Countries 
     {"Manila", "Seoul", "Tokyo", "Jerusalem" } // capital cities 
    }; 

    String outputString = String.format("%16s\t%9s", "Country", "City"); 
    System.out.println(outputString); 

    for(int col = 0; col < myArray[0].length; col++){ 
     System.out.printf("%16s\t%9s", myArray[0][col], myArray[1][col] ); 
     System.out.println();   
    } 
} 
0

考慮您陣不喜歡國際象棋的棋盤,你要訪問的每一行每一列,以參觀每平方,而更像是一個櫃子。

你知道有多少列。 (兩個)

因此,您只需循環查看第一列中的國家數量,並在第二列中查看每個條目的資本大小。