The compiler asked me to enable the return statement, although I already turned it on

I am new to Java and trying to solve the initial problem of finding the next prime number after a given number. Below are two versions of the solution that I came up with. For the first version, the compiler asks me to include the second return statement (i.e. return 0;) at the end of the findNextNumber method, although I already included the return statement in the code, and the second version did not ask me to include an additional return statement. Can someone please tell me why this is so? Thanks in advance for your help!

    public static int findNextPrime(int num) {

// VERSION 1
//        boolean isPrime = false;
//        while(!isPrime){
//            num += 1;
//            int sqt = (int)Math.sqrt(num);
//            for(int i = 2; i <= sqt; i++){
//                if(num % i == 0){
//                    break;
//                } else {
//                    isPrime = true;
//                    return num;
//                }
//            }
//        }
//        return 0;

// VERSION 2       
//        while (true) {
//            boolean isPrime = true;
//            num += 1;
//            int sqt = (int) Math.sqrt(num);
//            for (int i = 2; i <= sqt; i++) {
//                if (num % i == 0) {
//                    isPrime = false;
//                    break;
//                }
//            }
//            if (isPrime) {
//                return num;
//            }
//        }
    }
+4
source share
1 answer

In the second version, the compiler knows that it while(true) {...}can only be output by your return statement.

, , , while(!isPrime) {...} , isPrime - true. , , , return.

while(!isPrime) while(true) for(;;), , isPrime false.

+4

Source: https://habr.com/ru/post/1625243/


All Articles