1

I have two files in my Eclipse project. These are: PageRankSparse.java and PageRank.java. PageRank.java is finished, and I now wish to use some of its methods in PageRankSparse.java. I tried using one of them, subtract(), but got this compile error message:

Cannot make a static reference to the non-static method subtract(double[], double[]) from the type PageRank.

What is the reason for this error? Note that I never got this error when running PageRank.java. Here's the code:

public class PageRank {

    //Omitted declared constants for simplicity    

    public PageRank( String filename ) {

        int noOfDocs = readDocs( filename );
        NUMBER_OF_DOCS = noOfDocs;
        initiateProbabilityMatrix( noOfDocs );
        iterate( noOfDocs, 100 );
    }

    double[] subtract(double[] x, double[] y){
        if( !(x.length == y.length) ){
            throw new RuntimeException("vector dimensions must match in subtract()");
        }
        double[] z = new double[x.length];
        for(int i=0; i<x.length; i++){
            z[i] = x[i] - y[i];
        }
        return z;
    }


    public static void main( String[] args ) {
        if ( args.length != 1 ) {
            System.err.println( "Please give the name of the link file" );
        }
        else {
            new PageRank( args[0] );
        }
    }
}

PageRankSparse.java:

public class PageRankSparse {
    //Omitted declared constants for simplicity

    public PageRankSparse( String filename ) {
        int noOfDocs = readDocs( filename );
        NUMBER_OF_DOCS = noOfDocs;
        iterate( noOfDocs, 1000 );
    }

    void iterate( int numberOfDocs, int maxIterations ) {
            double[] a = new double[numberOfDocs];
            a[0] = 1;
            double[] aNew; 
            double[] diff;
            int i;
            for(i = 0; i<maxIterations; i++) {
                aNew = vDotHashMap(a, link);
                diff = PageRank.subtract(aNew, a); // ERROR IS HERE
                // the rest is not implemented
            }

    }

    public static void main( String[] args ) {
    if ( args.length != 1 ) {
        System.err.println( "Please give the name of the link file" );
    }
    else {
        new PageRankSparse( args[0] );
    }
    }
}
Sahand
  • 7,980
  • 23
  • 69
  • 137

1 Answers1

1

It is pretty clear. You can not call a non-static method outside the class without creating a new instance.

If you do wish call the method directly, you can add a static keyword to the method:

static double[] subtract(double[] x, double[] y)

xingbin
  • 27,410
  • 9
  • 53
  • 103