将一维数组转变成二维数组
解题思路
本题难点在于如何通过下标同时控制两个不同维度的数组,并进行赋值
1.对于二维数组,常见的方式是通过两层for循环,i、j,i是从0-m,而j经历了3此从0-n
2.而本题一维数组的下标i是一直在增长的,即从0-original.length
所以通过在外层循环增加索引cnt,初始值为0,在最内层先赋值再循环自增,保证了赋值过程的连续
点击查看代码
public class construct2DArray {
public static void main(String[] args) {
int[] original={1,2,3,4,5,6,7,8,9};int m =3, n =3;
int[][] array2D = new int[m][n];
if(original.length==m*n){
System.out.println("可以转换");
int cnt=0;
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
array2D[j][i]=original[cnt];
cnt++;
}
}
//[[1,2],[3,4]]
//[[1,2,3]]
System.out.print("[");
for (int j = 0; j <=m; j++) {
if (j<=m-1){
System.out.print("[");
}
for (int i = 0; i < n; i++) {
if(j<=m-1){
if (i<n-1){
System.out.print(array2D[j][i]+",");
}else {
System.out.print(array2D[j][i]+"]");
}
}
}
if (j<=m-2){
System.out.print(",");
}
}
System.out.print("]");
}else {
System.out.print("[]");
}
}
}