1

SO here is the method i call from the main. the first part just multiplies the methods together. It's the return that gets the errors and line 121. I emphisized the lines that get the errors. I want to multiply the matrix that was created with the multiplication of m and m2 with m, the original matrix continually. What is supposed to stop it from going forever is the while loop that will stop at 4. I know that probably not the best way. the call is this:

System.out.println(m.rec(m2));

m and m2 are clones.

public Matrix rec(Matrix m2) throws Exception{
    try{
        int v = 0;
        while(v < 4){
        if(c!=m2.r){
            System.out.println("Argh");
            throw new RuntimeException();
        }//if
        **m3=new Matrix(r, m2.c); LINE 121!!! <------ **
        for(int i=0; i<r; i++){
            for(int j=0; j<m2.c; j++){
                m3.data[i][j]=0;
                for(int k=0; k<c; k++){
                    m3.data[i][j]+= ( ( data[i][k]) )  *  (m2.data[k][j]);
                }//k
            }//j
        }//i
        v++;
        ** return m2.rec(m3); //LINE 131 <-------------**
        }//while
    }//try
    catch(Exception ex){
        System.out.println("Argh");
    }//catch
    return m2;
}//multiply

THIS IS THE ERROR, it prints the line 131 error thousands of times.

Exception in thread "main" java.lang.StackOverflowError
    at markovchain.Matrix.rec(Matrix.java:121)
    at markovchain.Matrix.rec(Matrix.java:131)
    at markovchain.Matrix.rec(Matrix.java:131)

1 Answers1

0

The while loop has no chance, since you execute in any case (with v = 0)

return m2.rec(m3); //LINE 131 <-------------**

and it goes right down into recursion hell.

You could limit recursion depth, maby by adding paramter level. Without understanding your algorithm fully, this is just a hint...

public Matrix rec(Matrix m2, int level) throws Exception{
    try{
        if (level > 4) {
            return m2;
        }
        int v = 0;
        while(v < 4){
        if(c!=m2.r){
            System.out.println("Argh");
            throw new RuntimeException();
        }//if
        **m3=new Matrix(r, m2.c); LINE 121!!! <------ **
        for(int i=0; i<r; i++){
            for(int j=0; j<m2.c; j++){
                m3.data[i][j]=0;
                for(int k=0; k<c; k++){
                    m3.data[i][j]+= ( ( data[i][k]) )  *  (m2.data[k][j]);
                }//k
            }//j
        }//i
        v++;
        ** return m2.rec(m3, level +1); //LINE 131 <-------------**
        }//while
    }//try
    catch(Exception ex){
        System.out.println("Argh");
    }//catch
    return m2;
}//multiply
Turo
  • 4,724
  • 2
  • 14
  • 27