2017-09-18 24 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

这是一个正确的方法。不知道它是否是最有效的。 –