将一维数组复制到二维数组 [英] Copying a 1d array to a 2d array
问题描述
所以我有作业要求我:
写一个带有两个参数的方法:一个整数数组和一个代表多个元素的整数.它应该返回一个二维数组,该数组是将传递的一维数组划分为包含所需数量的元素的行而得到的.请注意,如果数组的长度不能被所需数量的元素整除,则最后一行的元素数量可能会更少.例如,如果将数组
{1,2,3,4,5,6,7,8,9}
和数字4
传递给此方法,应该返回二维数组{{1,2,3,4},{5,6,7,8},{9}}
.
Write a method that takes two parameters: an array of integers and an integer that represents a number of elements. It should return a two-dimensional array that results from dividing the passed one-dimensional array into rows that contain the required number of elements. Note that the last row may have less number of elements if the length of the array is not divisible by the required number of elements. For example, if the array
{1,2,3,4,5,6,7,8,9}
and the number4
are passed to this method, it should return the two-dimensional array{{1,2,3,4},{5,6,7,8},{9}}
.
我尝试使用以下代码解决它:
I tried to solve it using this code:
public static int[][] convert1DTo2D(int[] a, int n) {
int columns = n;
int rows = a.length / columns;
double s = (double) a.length / (double) columns;
if (s % 2 != 0) {
rows += 1;
}
int[][] b = new int[rows][columns];
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (count == a.length) break;
b[i][j] = a[count];
count++;
}
}
return b;
}
但是我有一个问题,当我尝试打印新数组时,这就是输出:
But I had a problem which is when I try to print the new array this is the output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 0]]
那我怎样才能在最后删除3个零?请注意,我不能使用 java.util.*
中的任何方法或任何内置方法来实现此目的.
So how can I remove the 3 zeros at the end? Just a note that I can't use any method from java.util.*
or any built-in method to do this.
推荐答案
将2D数组的初始化更改为不包含第二维: new int [rows] []
.现在,您的数组中具有空数组.您必须在循环中初始化它们: b [i] = new int [Math.min(columns,remainingCount)];
其中,remainingCount是2d数组之外的数字量.
Change the 2D array's initialization to not contain the second dimension: new int[rows][]
. Your array now has null arrays inside it. You have to initialize those in your loop: b[i]=new int[Math.min(columns,remainingCount)];
where remainingCount is the amount of numbers outside the 2d array.
这篇关于将一维数组复制到二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!