如何使用我的代码制作此示例?我接近结果,但无法达到
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();
}
}
}
您需要的是
%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
因为您只是在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();
}
}