java - 锯齿状数组的顺序填充。这段代码是如何工作的?
问题描述
我正在通过锯齿状阵列上的解决方案之一,无法遵循以下几行。任何人都可以帮助我理解count
这里是如何使用的。我确实了解 Java 的基础知识,但不明白为什么在这里使用 count。
在 Java 中演示二维锯齿状数组的程序:
int arr[][] = new int[2][];
// Making the above array Jagged
// First row has 3 columns
arr[0] = new int[3];
// Second row has 2 columns
arr[1] = new int[2];
// Initializing array
int count = 0;//why do we need count
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++; //how this line of code will work
解决方案
您可以将输出添加到此代码。需要该count
变量来顺序地用整数填充数组,0
依此类推。
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
// iterate through the rows of the array
for (int i = 0; i < arr.length; i++)
// iterate through the columns of the array
for (int j = 0; j < arr[i].length; j++)
// set the array element and increment the counter
arr[i][j] = count++;
// output
for (int[] row : arr) System.out.println(Arrays.toString(row));
输出:
[0, 1, 2]
[3, 4]
推荐阅读
- java - 如何在 Java 中动态初始化数组?
- c# - 为什么发生异常时未从 Mvc 设置 StatusCode
- python - 在python中为groupby动态选择数据框列
- java - 需要 POJO 对象才能使用 Spring Boot 自动装配以下 yml 结构
- r - 通过检测一个字符串中的任何多个字符串模式来创建一个变量
- javafx - 尝试运行 javafx 应用程序时出错
- dialogflow-es - 如何在 Web 演示的对话流中添加链接或图像作为响应
- wso2 - WSO2 复合应用程序项目在向导中不显示任何依赖项
- javascript - 如何在没有 ReactJS 的情况下使用 Shopify Polaris?
- java - Log4J 2 查找值在加载/存在之前在配置中使用