java矩阵链乘法数组索引超出范围的异常

时间:2013-05-02 21:08:42

标签: matrix-multiplication indexoutofboundsexception

Trying to do chain matrix multiplication but the code throws an out of bound exception at 2 places, please help me eliminate it.
The exception occurs at 2 places
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
    at Recursive.Recursive_Matrix(Recursive.java:27)
    at Recursive.main(Recursive.java:15).

通过反复调用自身来使用以下递归的问题如下:

 mij =  0, if   i = j else it is

        min   ( mik + mk+1 j + ri-1 * rk * rj )    if  i < j
             i ≤ k < j

我认为它与MAX值相关的是99999.Or,这可能是由于其他一些比较。

 class Recursive{


    public static int SIZE = 7;
    public static int MAX = 99999;

    static int M[][] = new int[SIZE][SIZE];
    static int i, k, q, j;
    static int P[] = new int []  { 25,10,15,5,30,10,15};


    public static void main(String[] args)
    {

        Recursive_Matrix( 1, SIZE);
        Print_M();

       return;
    }

    static int Recursive_Matrix(int i, int j) 
    {
        if( i == j )
            return 0;
        else
        {
            M[i][j] = MAX;
            for(k = i; k <= j-1; k++)
            {
                q =  Recursive_Matrix(i, k) + Recursive_Matrix( k+1, j) +  ( P[i-1] * P[k] * P[j] );
                if( q < M[i][j])
                    M[i][j] = q;
            }
        }
        return M[i][j]; 
    }

//此函数仅用于打印矩阵的元素 //对角元素都是0,其他元素是从上面的递归函数计算出来的         static void Print_M()         {             for(int x = 1; x&lt; = SIZE; x ++)             {                 for(int y = 1; y&lt; = SIZE; y ++)                 {                     System.out.println(M [x] [y] +“”);                 }                 的System.out.println( “\ n”);             }         }         }

1 个答案:

答案 0 :(得分:0)

看看你的第一个电话Recursive_Matrix( 1, SIZE);。现在j=7以及之后...M[j]......P[j]...作为索引超出范围,以0开头。使用调试器并逐步执行代码!