您的位置:首页 > 产品设计 > UI/UE

循环结构中break和continue的替代方法(Repetition without break and continue statement)

2016-06-23 18:00 573 查看
需求说明:

循环体中使用break和continue语句,可以灵活实现循环的整体跳出和单次跳出。

然而,有评论认为,break和continue语句是“非结构化”的,不值得提倡。

于是,Java how to program的作者给我们学生留了这道题:请用其他控制语句实现break和continue功能。好的,1个多小时又耗在这了。


代码如下:

<pre class="java" name="code">//JHTP Exercise 5.26: Repetition without break and continue statement
//by pandenghuang@163.com
/**A criticism of the break statement and the continue statement is that each is unstructured.
Actually, these statements can always be replaced by structured statements, although doing so can
be awkward. Describe in general how you’d remove any break statement from a loop in a program
and replace it with some structured equivalent. [Hint: The break statement exits a loop from the
body of the loop. The other way to exit is by failing the loop-continuation test. Consider using in
the loop-continuation test a second test that indicates “early exit because of a ‘break’ condition.”]
Use the technique you develop here to remove the break statement from the application in
Fig. 5.13.*/

public class RemovalofBreakStatement
{
public static void main(String[] args)
{
int count; // control variable also used after loop terminates
boolean Break=false;
int size=20;
int[] skipCount=new int[size];

System.out.println("注意:输出以下内容的代码中未使用break,continue语句:");

//Normal for statement
for (count = 1; count<=size && Break!=true; count++) {// loop 10 times
System.out.printf("%d ", count);
}
System.out.printf("%n共迭代%d次,并完整执行了循环体%n%n", count-1);

//Removal of break statement
for (count = 1; count<=size && Break!=true; count++) // loop 10 times
{
if (count != 4  && Break==false)  // skip out of loop if count is 5
System.out.printf("%d ", count);
else
Break=true;
}

System.out.printf("%n共迭代%d次,并在第%d次迭代时整体跳出(break)了循环体%n%n", count-1,count-1);

//Removal of continue statement
for (count = 1; count<=size; count++) // loop 10 times
{
// skip the left statement in the loop if count is 4

if(count%10!=4){
System.out.printf("%d ", count);
}

else{
skipCount[count-1]=count;
}

}
System.out.printf("%n共迭代%d次,并在",count-1);
for(int i=0;i<size;i++){
if (skipCount[i]!=0)
System.out.printf("第%d次,",skipCount[i]);}
System.out.printf("单次跳出(continue)过循环体\n");
}
}



运行结果:

注意:输出以下内容的代码中未使用break,continue语句:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

共迭代20次,并完整执行了循环体

1 2 3

共迭代4次,并在第4次迭代时整体跳出(break)了循环体

1 2 3 5 6 7 8 9 10 11 12 13 15 16 17 18 19 20

共迭代20次,并在第4次,第14次,单次跳出(continue)过循环体



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: