如何将2D数组行并排打印成列?

时间:2017-09-18 19:47:12

标签: java arrays for-loop

这是我尝试解决问题的方法。我希望控制台窗口中的输出将2D数组的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");
}

3 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分: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++;
    }
}

答案 2 :(得分: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++;
}