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

来源:互联网 发布:幸福狐狸淘宝是真的吗 编辑:程序博客网 时间:2024/05/17 03:05

需求说明:

循环体中使用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 canbe awkward. Describe in general how you’d remove any break statement from a loop in a programand replace it with some structured equivalent. [Hint: The break statement exits a loop from thebody of the loop. The other way to exit is by failing the loop-continuation test. Consider using inthe 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 inFig. 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)过循环体





0 0
原创粉丝点击