【发布时间】:2019-01-11 18:05:36
【问题描述】:
我正在尝试翻转图像,我的方法是逐行反转 3X3 矩阵中的元素。我正在使用一个名为 matrix 的静态数组。
在 3 x 3 数组中插入值后,我将遍历数组的所有行并将值存储在 ArrayList 中。接下来,我在一个单独的函数中交换该列表中的元素,并尝试将交换的值插入函数的原始数组中(假设数组是静态的)。当我尝试这样做时,我得到一个索引超出范围的异常。我从头到尾尝试了一切,但这个问题似乎并没有消失。这是我的代码:
我已将打印语句用于检查传递、接收和交换后列表的大小。
import java.util.ArrayList;
import java.util.Scanner;
public class FlipAndInvert {
static int rows = 0;
static int columns = 0;
static int matrix[][] = new int[rows][columns];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Enter the dimensions of the array : ");
System.out.println("Enter # of Rows : ");
rows = input.nextInt();
input.nextLine();
System.out.println("Enter # of Columns : ");
columns = input.nextInt();
input.nextLine();
int matrix[][] = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print("Enter [" + i + "][" + j + "] : ");
int data = input.nextInt();
input.nextLine();
if (data == 0 || data == 1) {
matrix[i][j] = data;
} else {
System.out.println("Enter Binary Format");
}
}
}
for (int i = 0; i < rows; i++) {
ArrayList<Integer> store = new ArrayList<Integer>();
for (int j = 0; j < columns; j++) {
store.add(matrix[i][j]);
}
System.out.println("List Size Passed : " + store.size());
swap(store, i);
}
}
public static void swap(ArrayList<Integer> list, int r) {
int i = 0;
int j = list.size() - 1;
System.out.println("List Size Received : " + list.size());
if (list.size() % 2 == 1) {
// for odd list length
System.out.println("Inside if statememt");
while (j - i >= 2) {
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
i = i + 1;
j = j - 1;
}
System.out.println("List Size After Swap : " + list.size());
System.out.println("Outside while in if statememt");
System.out.println(matrix[0][0]);
} else {
// for even list length
while (j - i >= 1) {
int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
i = i + 1;
j = j - 1;
}
for (int c = 0; c < columns; c++) {
matrix[r][c] = list.get(c);
}
}
}
}
当我在最后一个 for 循环中替换数组中的元素时,我得到一个 Array Index Out of Bound 异常。任何人都可以在这里指导我。
【问题讨论】:
标签: java arrays arraylist data-structures indexoutofboundsexception