当我尝试交换值时,数组超出范围

时间:2011-04-16 20:53:31

标签: java multidimensional-array swap

我正在尝试交换2D数组中的值,但是我得到了“越界”运行时错误。

有什么问题?

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Q1
        int row = 3;
        int colum = 5;

        //Declare 2d array
        int [][] matrix = new int [row][colum];
        //Create array and input values
        Scanner input = new Scanner(System.in);
        System.out.println("Enter " + matrix.length + " rows and "
        + matrix[0].length + " colums: \n");
        for (row = 0; row < matrix.length; row++) {
            for (colum = 0; colum < matrix[row].length ; colum++) {
                matrix[row][colum] = input.nextInt();
        }
            }
        System.out.println("\nMultiplication table");
        System.out.println("--------------------");

        //Print the array
        for (row = 0; row < matrix.length; row++ ) {
            for (colum = 0; colum < matrix[row].length; colum++ ) {
                System.out.printf("%4d", matrix[row][colum]);
            }

            System.out.println();
        }
        //Q2 - Make the values swapable
        Scanner input1 = new Scanner(System.in);
        System.out.println("\n1: Modify a value. ");
        System.out.println("0: Exit the application");
        int selection = input1.nextInt();
        switch(selection) {
            case 0:
                System.exit(0);
                break;
            case 1:
                System.out.println("\nPlease enter the row you would like to change: "  );
                Scanner input2 = new Scanner(System.in);
                int changeRow = input2.nextInt();
                System.out.println("You entered: " + changeRow);
                System.out.println("Please enter the colum you would like to change: "  );
                Scanner input3 = new Scanner(System.in);
                int changeColum = input3.nextInt();
                System.out.println("You entered: " + changeColum);

    error--->   int temp = matrix[row][colum];
                matrix[row][colum] = matrix[changeRow][changeColum];
                matrix[changeRow][changeColum] = temp;

                System.out.println("The value in row " + changeRow + "and colum " + changeColum + "is now changed to " + temp);




                break;

            }
        }
    }

3 个答案:

答案 0 :(得分:1)

您在循环中使用rowcolumn。在循环之后检查它们的值。我不确定增量是否完成然后<检查失败,但如果确实如此,那么

int temp = matrix[row][colum];

正试图找到

matrix[3][5];

并且从0开始,这不存在。

答案 1 :(得分:1)

如果您发布了异常的堆栈跟踪,那么发现它会更容易。这是我的猜测:

 int temp = matrix[row][colum];

此处rowcolumn的值是多少?它们最后在循环中用于打印数组,因此您现在拥有row == matrix.lengthcolumn == matrix[row].length(前面有row值)。

当然,这超出了数组的允许范围,你得到IndexOutOfBoundsException。

答案 2 :(得分:0)

当你获得changeRow,changeColum输入时,你需要创建另一个数组初始化长度,然后通过比较以前的数组长度来分配值。