java实现把数组[1,2,3,5,6,7,9,10,11,13,14,15,19,20,21,22,24,25] 分成5个数组里,一个数组的容量为4,
时间: 2023-10-05 09:06:46 浏览: 70
可以使用循环和数组切片的方式来实现。
具体步骤如下:
1. 定义原始数组和目标二维数组。
```
int[] arr = {1,2,3,5,6,7,9,10,11,13,14,15,19,20,21,22,24,25};
int[][] targetArr = new int[5][4];
```
2. 循环遍历原始数组,每四个元素为一组,将其存放到目标二维数组中。
```
for (int i = 0; i < arr.length; i += 4) {
int groupIndex = i / 4;
targetArr[groupIndex] = Arrays.copyOfRange(arr, i, i + 4);
}
```
完整代码如下:
```
public class ArraySplit {
public static void main(String[] args) {
int[] arr = {1,2,3,5,6,7,9,10,11,13,14,15,19,20,21,22,24,25};
int[][] targetArr = new int[5][4];
for (int i = 0; i < arr.length; i += 4) {
int groupIndex = i / 4;
targetArr[groupIndex] = Arrays.copyOfRange(arr, i, i + 4);
}
for (int i = 0; i < targetArr.length; i++) {
System.out.println("Group " + i + ": " + Arrays.toString(targetArr[i]));
}
}
}
```
输出结果如下:
```
Group 0: [1, 2, 3, 5]
Group 1: [6, 7, 9, 10]
Group 2: [11, 13, 14, 15]
Group 3: [19, 20, 21, 22]
Group 4: [24, 25, 0, 0]
```
最后一组数组的最后两个元素为0,是因为原始数组的长度不足以填满最后一个数组,所以用0进行填充。
阅读全文