Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

java - "non-static variable this cannot be referenced from a static context"?

I'm a Java newbie and I'm trying to deploy a fibonacci trail through recursive function and then calculate the run time. here is the code I have managed to write:

class nanoTime{
    int fib(int n){
        if(n==0) return 0;
        if(n==1) return 1;
        return this.fib(n-1)+this.fib(n-2);
    }
    public static void main(String[] args){
        double beginTime,endTime,runTime;
        int n=10;
        beginTime = System.nanoTime();
        n = this.fib(n);
        endTime = System.nanoTime();
        runTime = endTime-beginTime;
        System.out.println("Run Time:" + runTime);
    }
}

The problem is when I'm trying to turn it into Byte-code I get the following error:

nanoTime.java:11: non-static variable this cannot be referenced from a static context

I'm wondering what is the problem?!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change

n = this.fib(n);

to

n = fib(n);

and make the method fib static.

Alternatively, change

n = this.fib(n);

to

n = new nanoTime().fib(n);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...