2017-09-18 26 views
1

這是我解決問題的嘗試。我希望控制檯窗口中的輸出讀取二維數組的3行作爲3列,並在列之間留出空間。如何獲得二維數組行以並排方式打印爲列?

for(int l = 0; l < studentsAnsNew.length; l++) { 
     for(int m = 0; m < studentsAnsNew[l].length; m++) { 
      System.out.print(" " + studentsAnsNew[l][m] + "\n"); 
     } 
     System.out.print("\t"); 
} 

回答

0

要打印現有的行爲列,反之亦然,改變

System.out.print(" " + studentsAnsNew[l][m] + "\n"); 

System.out.print(" " + studentsAnsNew[m][l] + "\n"); // notice the swapped indexes 

編輯:不要照顧改變數組的邊界,以及,假設您的代碼:

int rows = studentsAnsNew.length; 
int columns = studentsAnsNew[0].length; 

循環現在變爲:

for(int l = 0; l < columns; l++) { 
    for(int m = 0; m < rows; m++) { 
     System.out.println(" " + studentsAnsNew[m][l]); // changed to println 
    } 
    System.out.print("\t"); 
} 
+0

我建議改變循環邊界太 – harold

+0

@harold更新。謝謝 – nullpointer

+0

這不適合我。 –

0

將代碼段包含在while循環中。創建一個變量來增加。在每個循環中遞增該變量並將其用作數組中的引用。另外,刪除標籤空間。例如:

int temp = 0; 
while(temp<3){ 
    for(int l = 0; l < studentsAnsNew.length; l++) { 
     System.out.print(" " + studentsAnsNew[l][temp]); 
    } 
    System.out.print("\n"); 
    temp++; 
    } 
} 
+0

這也沒有效果。我不確定此時該做什麼。 –

+0

這將有助於看到您的代碼 – FossProgramBoss

+0

請參閱下面的答案。 –

0
int rowz = 0; 
int questionNumber = 1; 
for(int col = 0; col < studentsAnsNew[rowz].length; col++) { 
    System.out.printf("%2d)%2s\t\t", questionNumber, studentsAnsNew[rowz][col]); 
    System.out.printf("%3d)%2s\t\t", questionNumber, studentsAnsNew[rowz +1][col]); 
    System.out.printf("%3d)%2s\n", questionNumber, studentsAnsNew[rowz + 2][col]); 
    questionNumber++; 
} 
+0

這是一個正確的方法。不知道它是否是最有效的。 –