Reputation: 11
I wanted to keep it short. What happens after it returns true
? Does it stop the for
-loop and return to the do
-while
loop? I'm very confused; please provide a detailed description.
for (int i = 0; i < 6; i++)
{
int pick;
do
{
pick = (int) Math.floor(Math.random() * 50 + 1);
}
while (numberGone(pick, gui.numbers, i));
gui.numbers[i].setText("" + pick);
}
boolean numberGone(int num, JTextField[] pastNums, int count)
{
for (int i = 0; i < count; i++)
{
if (Integer.parseInt(pastNums[i].getText()) == num)
{
return true;
}
}
return false;
}
Upvotes: 0
Views: 4793
Reputation: 5297
The function always exits when a return
statement is encountered. No statement after that will be executed.
The only exception is try catch finally
block.
finally
block is always executed irrespective of whether return
is encountered before it or not.
Upvotes: 1
Reputation: 68715
A method returns the control as soon as it hits the first return
statement. Any code after the return
statement will not be executed. So in your code:
boolean numberGone(int num, JTextField[] pastNums, int count)
{
for (int i = 0; i < count; i++)
{
if (Integer.parseInt(pastNums[i].getText()) == num)
{
// if this is executed, execution of this method will return from here
return true;
}
}
// this will be executed only when if statement is not executed and for loop finishes gracefully
return false;
}
Note: If you don't want to return from the method when your if condition is met and simply end the loop then use break
instead of return
.
Upvotes: 2