我如何用Java中的这个锯齿状的数组作为例子

问题描述 投票:0回答:2

如何使用我的代码制作此示例?我接近结果,但无法达到

“此数组”

class Main { 
    public static void main(String[] args)   { 
        // Declare a 2-D array with 5 rows 
        int intArray[][] = new int[5][5]; 
          // create a jagged array that has i column(s) for ith row 
         for (int i=0; i<intArray.length; i++) 
           intArray[i] = new int[i+1]; 
          // Initialize the jagged array 
         int count = 1; 
         for (int i=0; i<intArray.length; i++) 
            for(int j=0; j<intArray[i].length; j++) 
               intArray[i][j] = count++; 

        // Display the values of 2D Jagged array 
       System.out.println("A two-dimensional Jagged Array contents:"); 
       for (int i=0; i<intArray.length; i++) 
        { 
           for (int j=0; j<intArray[i].length; j++) 
               System.out.print(intArray[i][j] + "  "); 
           System.out.println(); 
        } 
    } 
}
java arrays multidimensional-array
2个回答
0
投票

您需要的是

  • %2d将在2个空格中打印您的电话号码
  • 用0(即5-intArray [i] .length)填充剩余的块

       for (int j=0; j<intArray[i].length; j++) 
           System.out.printf("%2d ", intArray[i][j]); 
       for (int j=intArray[i].length ; j<5; j++) 
            System.out.printf("%2d ", 0); 
    

输出

A two-dimensional Jagged Array contents:

 1  0  0  0  0
 2  3  0  0  0
 4  5  6  0  0
 7  8  9 10  0
11 12 13 14 15

0
投票

您未制作完整的正方形2D阵列。您的数组如下所示:enter image description here

因为您只是在for循环中使每一行的大小i+1。删除那些初始化数组的行。然后,您将得到一个二维数组,其中填充了0。现在,您的其余代码将按预期工作:

public static void main(String[] args)   { 
    // Declare a 2-D array with 5 rows 
    int intArray[][] = new int[5][5]; 

    // Initialize the jagged array 
    int count = 1; 
    for (int i=0; i<intArray.length; i++) 
       for(int j=0; j<i+1; j++) 
           intArray[i][j] = count++; 

    // Display the values of 2D Jagged array 
   System.out.println("A two-dimensional Jagged Array contents:"); 
   for (int i=0; i<intArray.length; i++) 
    { 
       for (int j=0; j<intArray[i].length; j++) 
           System.out.print(intArray[i][j] + "  "); 
       System.out.println(); 
    } 
} 
© www.soinside.com 2019 - 2024. All rights reserved.