How to fix - 41: non-static variable cannot be referenced from a static context -> What is the reason for this?

馋奶兔 提交于 2019-12-02 06:51:24

listOfPrimeNumbers is a member of your class, which means that each instance of Primes has its own copy of listOfPrimeNumbers.

print is a static function, which means that it is not related to an instance of Primes, and as such, it doesn't have access to any of the listOfPrimeNumbers variables there are (one per instance of your class).

So listOfPrimeNumbers would have to be static (i.e. there is only one copy in the whole wide world), or print can't be static.

Your code isn't working because you aren't even using candidateNo in isPrime.

As for the difference between static things and non-static things, a non-static belongs to a specific instance, while a static belongs to the class.

You can't refer to a non-static from within a static method (or other static context) without first specifying which instance you're talking about. It'd be like if I said "what color are cars?" Your response would probably be something like "which car?".

Gazler

This is what you want if you wish to make an instantiated (non-static) call to the function. For the rest of the answer, see EboMike's answer.

Primes generator=new Primes(50);
generator.print();

  public void print( ) {
    int n = listOfPrimeNumbers.size();
    for(int i = 0; i <= n ; i++)
      System.out.println( listOfPrimeNumbers.get( i ) );

  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!