Java 移动2D数组元素时发生indexoutofbound错误 public static int[][]移位(最终int[][]原始,最终int金额){ int[][]移位=新int[original.length][original[0.length]; for(int col=0;col
嗨,Java 移动2D数组元素时发生indexoutofbound错误 public static int[][]移位(最终int[][]原始,最终int金额){ int[][]移位=新int[original.length][original[0.length]; for(int col=0;col,java,arrays,loops,Java,Arrays,Loops,嗨, 我正在尝试编写一种方法,将二维数组中的元素向左移动任意量。我不想循环这些值,而是用一些已经预定义的fill_值填充空数组。如果移位量大于原始长度,我只会返回一个只有fill_值的图像。但是,此函数正在抛出arrayindexoutofbound错误。但我想不出应该如何更改for循环来修复错误。感谢您的帮助!谢谢大家! 我相信这是因为在第二个外部for循环中,条件是cols0,它将继续通过数组的边缘。您可以使用调试器一步一步地检查代码,并准确地查看代码超出范围的位置。发生错误的原因是以下几行
我正在尝试编写一种方法,将二维数组中的元素向左移动任意量。我不想循环这些值,而是用一些已经预定义的fill_值填充空数组。如果移位量大于原始长度,我只会返回一个只有fill_值的图像。但是,此函数正在抛出arrayindexoutofbound错误。但我想不出应该如何更改for循环来修复错误。感谢您的帮助!谢谢大家! 我相信这是因为在第二个外部for循环中,条件是cols
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length + amount; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount < original.length) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
公共类溢出1{
静态int a[]]={{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8},{4,5,6,7,8,9},{5,6,7,8,9,10},{6,7,8,8,9,10};
静态int b[][];
静态int FILL_值=0;
公共静态整数[][]移位(最终整数[][]原始整数,最终整数金额){
int[][]移位=新int[original.length][original[0.length];
for(int col=0;col=0){
移位[列][行]=原始[列-金额][行];
}
}
}
}
收益转移;
}
公共静态void main(字符串[]arggs){
b=移位(a,2);
System.out.println(“原始数组:”);
对于(int i=0;我想这就是你所说的检查其超出边界的位置的意思。)这就是确切的错误消息“出错:java.lang.ArrayIndexOutOfBoundsException:-16”谢谢!
public class overflow1 {
static int a[][] = {{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8}, {4,5,6,7,8,9}, {5,6,7,8,9,10}, {6,7,8,9,10,11}};
static int b[][] ;
static int FILL_VALUE =0;
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length ; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount >=0) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
public static void main(String[] arggs) {
b=shift(a,2);
System.out.println("Original array:");
for(int i=0; i<a.length; i++){
for (int j=0; j<a[i].length; j++){
System.out.print(a[i][j]+ ":");
}
System.out.println();
}
System.out.println("After shift by 2 array:");
for(int i=0; i<b.length; i++){
for (int j=0; j<b[i].length; j++){
System.out.print(b[i][j]+ ":");
}
System.out.println();
}
}
}