
在java中 如何按列输出
用户关注问题
我有一个二维数组,想要按列而不是按行输出,应该怎么做?
使用两层循环按列遍历数组
在Java中,可以通过外层循环遍历列索引,内层循环遍历行索引来按列打印二维数组。例如:
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
System.out.print(array[row][col] + " ");
}
System.out.println();
}
这样可以实现按列输出每个元素。
除了按列输出,我还想让输出内容对齐,方便阅读,有什么建议?
使用格式化输出提高列对齐效果
可以使用String.format或System.out.printf方法固定每个元素的宽度,这样各列的数据能够整齐排列。例如:
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
System.out.printf("%-10s", array[row][col]);
}
System.out.println();
}
这里的%-10s表示左对齐且宽度为10的字符串。
如果不是二维数组,而是List<List<Object>>,怎样才能按列输出数据?
利用集合大小动态遍历实现按列输出
对于List<List>类型的数据,可以先确定最大行数和列数,然后通过列索引为外循环,行索引为内循环,访问对应位置的元素。需要注意越界检查。例如:
int maxRows = lists.size();
int maxCols = 0;
for (List row : lists) {
maxCols = Math.max(maxCols, row.size());
}
for (int col = 0; col < maxCols; col++) {
for (int row = 0; row < maxRows; row++) {
if (lists.get(row).size() > col) {
System.out.print(lists.get(row).get(col) + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}