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