我想编写一个函数,将2D数组的大小调整为给定的参数。其通用调整大小阵列:Java调整数组大小
public static int[][] resize(int[][] source, int newWidth, int newHeight) {
int[][] newImage=new int[newWidth][newHeight];
double scale=newWidth/source.length;
for (int j=0;j<newHeight;j++)
for (int i=0;i<newWidth;i++)
newImage[i][j]=source[(int)(i/scale)][(int)(j/scale)];
return newImage;
上面的代码没有问题,它适用于整数大小调整。然而,问题出现时,我使用resize函数调整数组的大小为0.5。
int[][] newImage=new int[source.length][source.length];
newImage=resize(source,source.length/2,source[0].length/2);
return newImage;
然后一切都变得疯狂。我得到了类似2147483647的outofboundserrorexception。问题在于第一个函数中的double scale
变量以及我在最后一行的第一个函数中使用的类型转换。任何想法修复?
注意:source.length是数组的宽度(列),source [0] .length是高度(行)。
2147483647恰好是2^31-1(java中signed int的最大值)。巧合?我想不是。快乐的编码。 – 2010-10-09 23:22:52
[Java Array Manipulation]的可能重复(http://stackoverflow.com/questions/3886818/java-array-manipulation) – 2010-10-09 23:33:04
SO缺少的是一组通用答案,向学生程序员解释如何调试程序。 – 2010-10-10 02:25:22