Just started learning java and I can't understand what's wrong with my code. PrimeIterator is supposed to generate infinite amount of prime numbers (starting from a number 3) but when I print the output I get: 3, 5, 7, 9, 11, 13, 15 etc.
public class Prime {
PrimeIterator iter = new PrimeIterator();
private class PrimeIterator implements java.util.Iterator<Integer>
{
int numb = 1;
public boolean hasNext()
{
return true;
}
public Integer next()
{
nextCandidate:
do{
numb += 2;
int numbSqrt = (int)java.lang.Math.sqrt(numb);
for (int i = 3; i <= numbSqrt; i = i+2)
{
if (numb % i == 0)
{
continue nextCandidate;
}
}
}while(false);
return numb;
}
public void remove() {}
}
void printPrimes()
{
System.out.print(2);
while(iter.hasNext())
{
try
{
Thread.sleep(500);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(", " + iter.next());
}
}
}
I wanted to use labelled "continue" statement for my do-while loop. However my intuition tells me that I use it incorrectly.