如果我的问题措辞不好,我想首先道歉。我有一个考试tmmrw,教授给了我们一个期末考试样本供我们练习。不幸的是,他没有在论坛上回复解决方案,所以我试图在那里提供解决方案。我似乎被这个问题困住了。我必须编写一个方法,接受 NxM 数组填充整数值作为参数。方法是返回一个 (N+1)x(M+1) 数组,该数组包含原数组前 N 行 M 列的内容以及每行/列中大于或等于 0 的项数在该行/列的末尾并将值 -1 放在右下角。例如。
1 -2 0 returns 1 -2 0 2
3 -4 -5 3 -4 -5 1
2 0 1 -1
我似乎能够复制数组,但我对如何在新数组的外部输入值感到困惑。这是我到目前为止所拥有的。
public static void main(String[] args) {
int[][] arr = { { 1, -2, 0 }, { 3, -4, -5 } };
int[][] newMatrix = processing2D(arr);
printArray(newMatrix);
}
//Method where I am having problems
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length][arr[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
matrix[row][col] = arr[row][col];
}
}
// assign the corner -1 here
return matrix;
}
public static void printArray(int[][] list) {
for (int row = 0; row < list.length; row++) {
for (int col = 0; col <= list.length; col++) {
System.out.print(list[row][col] + " ");
}
System.out.println();
}
}
最佳答案
首先,您初始化的新数组应该是错误的
int[][] matrix = new int[arr.length+1][arr[0].length+1];
您不希望它的长度与您希望它的长度+1 的长度相同。另外,在 for 循环中,您想要按 arr 的长度而不是矩阵的长度,因为这就是您要从中获取的内容。将值放入新的 N+1xM+1 数组时,如果该行和列中相应的最后一个元素的值 >=0,则将其值加 1。
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(arr[row][col]>=0){
matrix[row][matrix[row].length-1] = matrix[row][matrix[row].length-1] + 1;
matrix[matrix.length-1][col]= matrix[matrix.length-1][col] + 1;
}
matrix[row][col] = arr[row][col];
}
将所有值放回新的 N+1xM+1 数组后,您现在应该取出 n 大小和 m 大小的数组中的值,并将它们放入 N+1xM+1 数组中的相应槽中。之后只需手动将-1 放在右下角慢速即可。
matrix[matrix.length-1][matrix[0].length-1]=-1;
关于java - 复制二维数组并增加大小以填充新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34259406/