Dividing a 1D array into 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.
推荐答案
将二维数组的初始化更改为不包含第二维:new int[rows][]
.您的数组现在里面有空数组.您必须在循环中初始化它们:b[i]=new int[Math.min(columns,remainingCount)];
其中 remainingCount 是二维数组之外的数字数量.
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.
这篇关于将一维数组划分为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将一维数组划分为二维数组
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01