[英]How can i make this example with this jagged array in java
How can i make this example with my codes?我怎样才能用我的代码制作这个例子? I approached the result but I could not reach
我接近了结果,但我无法达到
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();
}
}
}
What you need is你需要的是
%2d
which will print your number in 2 spaces %2d
将在 2 个空格中打印你的号码to fill the remaining of blocks with 0 ( ie 5-intArray[i].length)用 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);
Output Output
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
You are not making a complete square 2D-array.您不是在制作完整的方形二维阵列。 Your array is like the following:
您的数组如下所示:
Because you are just making every row's size i+1
in your for loops.因为您只是在 for 循环中使每一行的大小
i+1
。 Delete those lines that initialize the array.删除那些初始化数组的行。 Then you have a 2D array which is filled with
0
s.然后你有一个二维数组,其中填充了
0
s。 Now the rest of your code will work as you expect:现在,您的代码 rest 将按预期工作:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.