简体   繁体   中英

How do I break out of this loop?

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

Remove the semi-colon that is terminating your for loop

for (i=2; i<num; i++);{
                     ^

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM