I'm writing the following code purely for fun and there are probably still errors or it may not even work at all:
public class PrimeGenerator implements PrimitiveIterator.OfInt {
private final static IntNode HEAD_NODE = new IntNode(2); //error here
private IntNode lastNode = HEAD_NODE;
private int current = 0;
@Override
public boolean hasNext() {
return true;
}
@Override
public int nextInt() {
if (lastNode.value == current) {
lastNode = lastNode.next;
return lastNode.value;
}
while (true) {
current++;
if (isPrime(current)) {
break;
}
}
appendNode(current);
return current;
}
private boolean isPrime(final int number) {
PrimeGenerator primeGenerator = new PrimeGenerator();
int prime = 0;
while (prime < number) {
prime = primeGenerator.nextInt();
if (number % prime == 0) {
return false;
}
}
return true;
}
private void appendNode(final int value) {
couple(lastNode, new IntNode(value));
}
private void couple(final IntNode first, final IntNode second) {
first.next = second;
second.previous = first;
}
private class IntNode {
public final int value;
public IntNode previous;
public IntNode next;
public IntNode(final int value) {
this.value = value;
}
}
}
For people not known with Java 8, don't worry, PrimitiveIterator.OfInt, works the same as Iterator<Integer>.
The issue I am having is on the second line, namely the:
private final static IntNode HEAD_NODE = new IntNode(2);
I get the warning: non-static variable this cannot be referenced from a static class.
I have searched and it should be able to be fixed by making IntNode non-dependant on PrimeGenerator, by moving it in its own public class.
However, what can I do if I do not want IntNode to be publicly known?
staticclass?