"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?!
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.
The problem is just what the message says. Your main
method is static
, which means it is not linked to an instance of the nanoTime
class, so this
doesn't mean anything. You need to make your fib
method static
as well, and then use nanoTime.fib(n)
.
There is no reason to use this
in your code.
Steps to take:
- Rename your class to anything that starts with an upper case letter
- Remove all
this
from your code - Add the
static
keyword beforeint fib(int n){
- Finally get a good Java book! ;)
# Name the class something else to avoid confusion between System.nanoTime and the name of your class.
class nanoTime1{
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();
# Instantiate an object of your class before calling any non-static member function
nanoTime1 s = new nanoTime1();
n = s.fib(n);
endTime = System.nanoTime();
runTime = endTime-beginTime;
System.out.println("Run Time:" + runTime);
}
}
Be careful ! In Java the main has to be in a class definition, but it's only the entry point of the program and absolutely not a method of the object/class.
Change this.fib(n)
to :
nano obj = new nano();
n = obj.fib(n);
this
is associated with the instance of the class. A static method does not run with a class instance but with the class itself. So either change the fib
method to static
or replace the line where you call fib
to the above two lines.
精彩评论