java 动态创建二维数组
时间: 2023-11-29 08:46:28 浏览: 83
以下是Java动态创建二维数组的方法:
```java
int m = 3; // 行数
int n = 4; // 列数
int[][] a = new int[m][n]; // 创建一个m行n列的二维数组
// 给二维数组赋值
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = i * n + j;
}
}
// 输出二维数组
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
```
上述代码中,首先定义了行数m和列数n,然后使用`new`关键字创建一个m行n列的二维数组。接着使用两个嵌套的`for`循环给二维数组赋值,最后再使用两个嵌套的`for`循环输出二维数组。
相关问题
java如何动态创建二维数组
Java中动态创建二维数组可以使用以下方式:
```java
int[][] arr = new int[n][m];
```
其中,n和m分别表示二维数组的行数和列数。这种方法只能创建静态的二维数组。
如果想要动态创建二维数组,可以使用以下代码:
```java
int n = 3; // 行数
int m = 4; // 列数
int[][] arr = new int[n][];
for(int i = 0; i < n; i++) {
arr[i] = new int[m];
}
```
这样就可以动态创建一个3行4列的二维数组了。注意,这里只指定了行数,而没有指定列数,因为每行的列数可能不同,所以需要在循环中逐行分配列数。
java实现动态创建二维数组并遍历输出
可以使用以下代码实现动态创建二维数组并遍历输出:
```
int[][] array = new int[3][4];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = i + j; // 可以根据需要给数组元素赋值
System.out.print(array[i][j] + " ");
}
System.out.println();
}
```
上述代码中,我们创建了一个3行4列的二维数组。在两层循环中,我们遍历整个数组,并输出每个元素的值。在这里,我们给每个元素赋值为行号和列号的和,方便输出验证。
阅读全文
相关推荐













