仅仅学了些简单内容,刚刚接触二维数组,用空格替代前面的数如何替代呢
遍历到某一行的时候,用元素最多的一行的个数减去当前行的个数,得到的差值n就是需要输出的空格数。
先System.out.print(' ') n次,然后再println()当前行的数据
public class Test {
private static final char[][] table = new char[][] { { 'a' }, { 'a', 'b', 'c', 'd' }, { 'a', 'b' } };
public static void main(String[] args) throws Exception {
int max = 0;
int[] length = new int[table.length];
for (int i = 0; i < table.length; i++) {
length[i] = table[i].length;
max = Math.max(max, length[i]);
}
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < max - length[i]; j++) {
System.out.print(' ');
}
System.out.println(table[i]);
}
}
}
将二维动态数组尾部对齐是什么意思?每行的元素个数相同吗?