我想在每行打印出数组中越来越多的元素,但我不确定如何做到这一点。
public static void main(String[] args) {
int[] x = new int[21];
for (int i = 0; i < x.length; i++) {
x[i] = i + 1;
}
System.out.println(Arrays.toString(x));
}
我希望我的输出看起来像:
[1]
[2, 3]
[4, 5, 6]
etc...
而不是我现在得到的
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
我对java真的很陌生,所以任何提示都会非常感激,谢谢。
最佳答案
将此添加到您的代码下方。
for (int i = 0, ctr = 0; i < x.length; ctr++) {
System.out.print("[ ");
for (int j = 0; j <= ctr; i++) {
System.out.print(x[i]);
j++;
if (j <= ctr) {
System.out.print(" ,");
}
}
System.out.println(" ]");
}
关于java - 如何每行打印越来越多的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54758884/