如何每行打印越来越多的数组元素

时间:2019-02-19 04:31:07

标签: java arrays

我想在每行中打印出阵列中越来越多的元素,但是我不确定该怎么做。

 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真的很陌生,所以非常感谢任何提示。

4 个答案:

答案 0 :(得分:0)

将此添加到您的代码下方。

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(" ]");
}

答案 1 :(得分:0)

使用两个循环可以获得结果,外部循环将在每次迭代中创建一个空数组,内部循环将在其中填充数字。还使用第三个变量来跟踪生成的最后一个数字。

public static void main(String[] args) {
       int n = 21;
       int lastNumber = 0;
       int x[] = null;
       for(int j = 0; j< n; j++) {
            x = new int[j];
            for (int i = 0, k = lastNumber; i< j; i++,k++) {
                x[i] = k + 1;
            }
            if(x.length != 0){
                lastNumber = x[x.length - 1];
                System.out.println(Arrays.toString(x));
            }
      }
 }

输出:

[1]
[2, 3]
[4, 5, 6]
[7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20, 21]

答案 2 :(得分:0)

此方法不需要存储

int start = 1;
int count = 1;
int outer = 6;
for (int y = 0; y < outer; y++) {
   System.out.print ("[");
   int x = start;
   for (; x < start + count; x++) {  
       System.out.print (x);
       if (x < start + count - 1) 
           System.out.print(","); 
   }
   System.out.println ("]");
   count++;
   start = x;
}

结果

[1]
[2,3]
[4,5,6]
[7,8,9,10]
[11,12,13,14,15]
[16,17,18,19,20,21]

答案 3 :(得分:0)

您可以使用此代码

        int[] x = new int[21];
        for (int i = 0; i < x.length; i++) {
            x[i] = i + 1;
        }
        int start = 0, len = 1;
        while(start + len <= x.length) {
            int[] newArray = Arrays.copyOfRange(x, start, start + len);
            System.out.println(Arrays.toString(newArray));
            start += len;
            len++;
        }