1

I'm trying to write this code to get the first initialCapacity prime numbers and then print them in sequence using java. It isn't working for two reasons, firstly I get the error

41: non-static variable listOfPrimeNumbers cannot be referenced from a static context

when I try to run the program, but even when I change the variable to static and run the program, it will only print out "1". So it is only iterating the while loop in the constructor Primes once, and then stopping and I simply cannot find the problem there no matter how hard I look ! Would anyone be able to help me out please, even if you could just give a very quick look and tell me what could be wrong, I'd really appreciate it.

Also, what is the story with relation to non-static and static variables and methods ? What is the best practice when using these ? If anyone could link me to a page describing this (I have googled to no avail!) I would love to read up :)

Thank you all so much !

import java.util.*;
public class Primes {
  private ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);    
    int index=0;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    //in here ! ?
    int i=2;
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%i==0 && i!=1) {
        return false;
      }
    }
    return true;
  }

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

  }
}

I have edited my code now so that everything is static (meaning I can have multiple instances?). I now have this, the problem being it just prints out the first 51 numbers, and then gets a stack overflow, can anyone help ? Thank you :) :

import java.util.*;
public class Primes {
  private static ArrayList<Integer> listOfPrimeNumbers;

  public static void main(String[] args) {
    ArrayList<Integer> listOfPrimeNumbers;
    Primes generator=new Primes(50);
    print();
  }

  public Primes( int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);    
    int index=2;
    int counter=0;
    while (counter != initialCapacity  ) {
      if (isPrime(index)) {
        listOfPrimeNumbers.add(index);
        counter++;
        System.out.println(counter);
        index++;
      }
      else {
        index++;
      }
    }
  }
  public boolean isPrime(int candidateNo) {
    Iterator<Integer> iter = listOfPrimeNumbers.iterator( );
    while ( iter.hasNext( ) ) {
      int next = iter.next( );
      if (next%candidateNo==0 && candidateNo!=1) {
        return false;
      }
    }
    return true;
  }

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

  }
}
user476033
  • 4,607
  • 8
  • 32
  • 35
  • possible duplicate of [non-static variable cannot be referenced from a static context (java)](http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context-java) – Don Roby Nov 29 '10 at 22:56

3 Answers3

5

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.

EboMike
  • 76,846
  • 14
  • 164
  • 167
3

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?".

Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • Thank you very much for the response ! I can't believe I missed the silly problem with the isPrime method. I have edited my post to include my new code now, but it is still giving me a problem. Can you see anything that I am doing wrong ? – user476033 Nov 29 '10 at 23:13
  • 1
    You are checking if your known primes are divisible by your candidate. You want to check if your candidate is divisible by a known prime. – Laurence Gonsalves Nov 29 '10 at 23:17
  • BTW: you can replace the first 3 lines of isPrime with: `for (int next : listOfPrimeNumbers) {` -- shorter and easier to read. – Laurence Gonsalves Nov 29 '10 at 23:18
  • Of course ! Thank you ! Its printing the primes now I switched the variables in the if statement around...it's doing it forever, but its a distinct improvement ! Thank you so much ! :) – user476033 Nov 29 '10 at 23:20
  • @user476033, in the future you should probably try to avoid 2-part questions. After the original was answered it would probably have been appropriate to post a second question specific to whatever the next problem you encountered was. Having read this (an hour later) it is confusing to try to discern the way this posting evolved. – Tim Bender Nov 30 '10 at 00:06
0

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

  }
Community
  • 1
  • 1
Gazler
  • 83,029
  • 18
  • 279
  • 245