简体   繁体   中英

Why can't I write a return statement inside a loop?

I'm writing a function that gives me the largest factor that is a prime number of a number. So for example, the number 12 will give me 3. My initial code was:

public static int getLargestPrime(int number) {
        if (number < 2) {
            return -1;
        }

            for (int num = 2; num <= number; num++) {
                int mod = number % num;
                if (mod == 0) {
                    int div = number / num;
                    if (div == 1) {
                        return number;
                    } else {
                        number = div;
                        num = 1;
                    }
                }
            }
    }

But I keep getting a missing return statement error so I added one:

public static int getLargestPrime(int number) {

        if (number < 2) {
            return -1;
        }

            for (int num = 2; num <= number; num++) {
                int mod = number % num;
                if (mod == 0) {
                    int div = number / num;
                    if (div == 1) {
                        return number;
                    } else {
                        number = div;
                        num = 1;
                    }
                }
            }
            return number;
    }

It is now correct, but I don't quite understand the logic behind it. I have read that there are some situations that the loop will not execute hence I need to return something even if my loop does not execute however I cannot think of any situations where my loop will not execute. Literately anything 2 or above will trigger the loop and anything less than 2 will return -1. So my question is in what situations will the loop not execute? And also, the return statement after the for loop does not really make sense, is there a better way of solving the missing return statement?

In your initial code:

if (div == 1) {
    return number;
} else {
    number = div;
    num = 1;
}
                    }

In case when you'll always have false, you will never reach return statement. Compiler does not predict if it will actually happen so it requires return statements in both if and else blocks. So it actually has nothing to do with for loop.

Two suggestions 1. It is better not to change the parameter you passed ( In this case number variable) 2. Have as few return statements as possible.

In your case, you can declare another variable tempNumber outside the for-lopp and assigned with 'number'. In the if condition where you are returning, there you 'break'. Return the number at the end of the function. That way always number is returned

public static int getLargestPrime(int number) {

    if (number < 2) {
        return -1;
    }

    int tempNumber = number;
    for (int num = 2; num <= tempNumber; num++) {
        int mod = tempNumber % num;
        if (mod == 0) {
            int div = tempNumber / num;
            if (div == 1) {
                break;
            } else {
                tempNumber = div;
                num = 1;
            }
        }
    }
    return tempNumber;

}

I cannot think of any situations where my loop will not execute

It is mandatory to write methods in a valid, well defined way. See it as a form to help the compiler.

The existence of a return statement is checked at compile time. If the compiler finds a possible execution branch that does not end in a valid return statement (or an explicitly thrown exception) it runs into an error. Read more .

Even ...

int method() {
    if (true)
        return 1;
}

... will fail to compile with

This method must return a result of type int

https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14

The Java compiler does not verify your code inside your loop, so you need to put return statement all of your forks. Coverage tests will warn you because you have an unreachable code, so you need re-planning your code.

NOTE: you need check your prime test until or equals Math.sqrt(number) , if larger than this sqrt without divider, you can break your loop and return the number

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