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?!
There is one simple way of solving the non-static variable cannot be referenced from a static context error. Address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.
And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.
Of course, they can, but the opposite is not true, i.e. you cannot obtain a non-static member from a static context, i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs to.
You cannot assign the result of a non-static method to a static variable. Instead, you would need to convert the getIPZip method to be a static method of your MyProps class, then you could assign its result to yor IPZip variable like this. public static String IPZip = MyProps. getIPZip("IPZip");
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);
                        You need to instantiate a nanoTime to call an instance method, or make the fib method static as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With