While (return value will terminate an iteration or loop?)
Code :
while (true) {
System.out.print("Your Guess: ");
input = scanner.nextInt();
if (LOWER_BOUND <= input && input <= UPPER_BOUND) {
return input;
}
this is a chunk of the whole code that i've written, a simple development exercise in the book
my question is....is this part will terminate a loop?
Code :
if (LOWER_BOUND <= input && input <= UPPER_BOUND) {
return input;
im a bit curious about a returning value... when this statement is statisfied? will the loop stop?
if there something unclear about my codes. let me know , ill post the whole code for you...
Re: While (return value will terminate an iteration or loop?)
No it will not terminate the loop unless you insert a "break;"
Code :
if (LOWER_BOUND <= input && input <= UPPER_BOUND) {
return input;
break;
Re: While (return value will terminate an iteration or loop?)
Return statements do return out of "infinite loops" (though, technically this makes those loops not infinite loops anymore :P )
However, more than the loop will be escaped from. The method will be terminated and the value immediately returned.
As a side note, throwing exceptions can break out of loops/methods so long as they are caught outside the loop
Code :
try
{
while (true)
{
// break out of this while loop
throw new Exception();
}
}
catch(Exception e)
{
System.out.println("The loop was escaped from!");
}
As a sidenote, that logic is inefficient.
Assuming that UPPER_BOUND is always bigger than LOWER_BOUND, it's more efficient to only check if the value is lower than LOWER_BOUND.
Re: While (return value will terminate an iteration or loop?)
Yes, whenever you call return you end the method stack and return the value specified, no matter where you are.
If you wish to break out of loops but stay in the method, have a look at the "break" keyword and labels.
// Json