I have often heard that using breaks in Java is considered bad practice, but after reading some threads on Stack Overflow, I've seen otherwise. Many say that it is acceptable in certain cases.
I'm a little confused as to what is/isn't bad practice in this case.
For Project Euler: Problem 7, I've constructed the code below. The challenge was to find the 10001st prime.
int index = 2, count = 1, numPrime = 1;
while (true) {
index++;
if (isPrime(index)) {
count = index;
numPrime++;
}
if (numPrime >= 10001)
break;
}
System.out.println(count);
This returns the correct answer (in 21ms), but am I overlooking a serious warning? It's 100% possible to create a while loop without a break, but I find that this is a little easier to follow.
Is the way I use the break; bad practice? I know that there's always a way around using one, but is it really that terrible here?
Many thanks
Justian
EDIT
Here's my isPrime() code. I might as well optimize this while I'm at it.
public static boolean isPrime(long num) {
if (num == 2)
return true;
if (num % 2 == 0 || num <= 0)
return false;
for (long i = 3; i * i <= num; i += 2)
if (num % i == 0)
return false;
return true;
}