【问题标题】:Index out of bounds exception when trying to swap the colums of a matrix尝试交换矩阵的列时索引超出范围异常
【发布时间】:2015-01-23 17:59:00
【问题描述】:

我正在尝试交换矩阵的列,但我从 bouds 异常中得到了一个数组索引。矩阵就是这张图的转换:http://i.imgur.com/NcYPgRO.jpg

public static void especular(int [][] img){
        for (int f=0; f<img.length;f++)
            for (int c=0; c < img[f].length/2;c++){
                int aux = img[f][c];
                img[f][c] = img[f][img.length-1-c];
                img[f][img.length-1-c] =aux;
            }
    }

【问题讨论】:

  • 数组是方阵吗?

标签: java for-loop matrix indexoutofboundsexception


【解决方案1】:

这是因为你的行和列不一样。

考虑一个例子: 一个 3x4 矩阵

[1,2,3] [4,5,6] [7,8,9] [10,11,12]

现在交换行和列

[1,4,7,10] [2,5,8,11] [3,6,9,12]

这变成了一个 4x3 矩阵


编辑:

public static void main(String[] args) {
    int [][] arr={{1,2,3},{4,5,6},{7,8,9}};
    printArray(arr);
    System.out.println();
    swapAllcolumns(arr);
}

public static void printArray(int [][] arr){
    for(int i =0; i<arr.length;i++){
        for(int j=0;j<arr[0].length;j++){
            System.out.print(arr[i][j]+" ");
        }
        System.out.println();
    }
}

public static void swapAllcolumns(int [][] array){
    int [][] arr= new int[array.length][array[0].length];
    for(int i =0; i<arr.length;i++){
        for(int j=0;j<arr[0].length;j++){
            arr[i][j]=array[i][array[0].length-j-1];
        }
    }
    printArray(arr);
}

输出

1 2 3 
4 5 6 
7 8 9 

3 2 1 
6 5 4 
9 8 7 

【讨论】:

  • 这不是我想要做的。以您的示例为例,我要做的是: [3,2,1][6,5,4][9,8,7][12,11,10]
【解决方案2】:

在我看来,您已经交换了二维数组中的 x 和 y 坐标。 我能够用这个数组重现这个问题:

int[][] testArray = new int[482][446];

但是这个有效:

int[][] testArray = new int[446][482];

但我会专注于编写一个不依赖图像尺寸的循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2017-02-12
    • 2013-03-22
    • 1970-01-01
    相关资源
    最近更新 更多