您将无法仅使用return 或break 退出if 条件。
return 用于在方法执行完成后需要从方法返回,而您不想执行其余的方法代码。所以如果你使用return,那么你不仅会从if条件返回,还会从整个方法返回。
考虑以下方法:
public void myMethod()
{
int i = 10;
if(i==10)
return;
System.out.println("This will never be printed");
}
在这里,使用return 会导致在第 3 行之后停止整个方法的执行,并返回到其调用者。
break 用于脱离loop 或switch 语句。考虑这个例子 -
int i;
for(int j=0; j<10; j++)
{
for(i=0; i<10; i++)
{
if(i==0)
break; // This break will cause the loop (innermost) to stop just after one iteration;
}
if(j==0)
break; // and then this break will cause the outermost loop to stop.
}
switch(i)
{
case 0: break; // This break will cause execution to skip executing the second case statement
case 1: System.out.println("This will also never be printed");
}
这种类型的break 语句称为unlabeled break 语句。还有另一种中断形式,称为labeled break。考虑这个例子 -
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++)
{
for (j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == searchfor)
{
foundIt = true;
break search;
}
}
}
此示例使用嵌套的 for 循环来搜索二维数组中的值。找到该值后,带有标签的 break 会终止外部 for 循环(标签为“搜索”)。
您可以从JavaDoc 了解更多关于break 和return 语句的信息。