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; // } // } }
In the second version, the compiler knows that it while(true) {...}can only be output by your return statement.
while(true) {...}
, , , while(!isPrime) {...} , isPrime - true. , , , return.
while(!isPrime) {...}
isPrime
while(!isPrime) while(true) for(;;), , isPrime false.
while(!isPrime)
while(true)
for(;;)
Source: https://habr.com/ru/post/1625243/More articles:How to use BeautifulSoup to get deeply nested div values? - pythonPrintWriter - a new line. Works great in Eclipse - javaAll MySQL records for yesterday - mysqlHow to calculate grades from script_fields in elasticsearch? - elasticsearchProgrammatically change focus after entering text in UITextfield - objective-cYouTube Channel Subscription for Android - androidIs it true that JOINS can be used everywhere to replace subqueries in SQL - sqlкак преобразовать коврик в изображение в (Emgu CV версии 3) в С#? - c#Безопасное установление ключей с помощью StackExchange.Redis, позволяя удалять - redisKartik / Krajee Select2 not disabled - phpAll Articles