Reputation: 55
I'm new to Java and am in quite a fix. Forgive me if this sounds like a really simple question.
This is a prime number checker question where I have to return 1 if it is and 0 if it is not a prime number. I have a simple code here but how do I break out of the loop? I am always getting the error 'break outside switch or loop'. Is my break not in a loop?
public class PrimeNumberChecker {
public static int isPrime(int num){
int bin = 1;
int i;
for (i=2; i<num; i++);{
if (num%i==0){
bin=0;
break;
}
}
return bin;
}
}
Upvotes: 3
Views: 174
Reputation: 1108
When you terminate for loop with ;, it equivalent
to
if (num%i==0){
bin=0;
break;
}
Or in other word your for loop doesn't have body. and break statement are used for terminating loops, but you ended using it outside loop.
Just rewrite your for loop as :
for (i=2; i<num; i++){
if (num%i==0){
bin=0;
break;
}
}
Upvotes: 2
Reputation: 159784
Remove the semi-colon that is terminating your for
loop
for (i=2; i<num; i++);{
^
Upvotes: 13