我想保持简短。返回true
后会发生什么?它是否会停止 for
循环并返回到 do
-while
循环?我很困惑;请提供详细说明。
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;
}
最佳答案
方法在遇到第一个 return
语句后立即返回控件。 return
语句之后的任何代码都不会被执行。所以在你的代码中:
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;
}
注意:如果您不想在满足 if 条件时从方法返回并简单地结束循环,请使用 break
而不是 return
。
关于java - for 循环中 if 语句中的 return 语句之后会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18244564/