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

Categories

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

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

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...