continue,return,break

Posted on 2006-05-23 22:29  苹果引擎  阅读(1664)  评论(0)    收藏  举报

1。单层循环

using System;

namespace ConsoleApplication7
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 class Class1
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   //
   // TODO: 在此处添加代码以启动应用程序
   //
   for (int i=0;i<10;i++)
   {
    if (i==7) continue;
//continue后跳过本次循环中的其他语句,继续下次循环
//    if (i==7) break;
//
break跳出整个循环继续执行循环后的语句
//    if (i==7) return;
//ruturn跳出整个程序直接返回

    Console.WriteLine(i);
   }
Console.WriteLine("This is the end.");
   }
 }
}

 if (i==7) continue;的运行结果:
0
1
2
3
4
5
6
8
9
This is the end.
 

if (i==7) break;的运行结果:
0
1
2
3
4
5
6
This is the end.

if (i==7) return;的运行结果:
0
1
2
3
4
5
6

2。嵌套循环

using System;

namespace ConsoleApplication7
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 class Class1
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   //
   // TODO: 在此处添加代码以启动应用程序
   //
   for (int i=0;i<10;i++)
   {
     for (int j=0;j<10;j++)
    {
//         if (i==7) continue;
//         if (i==7) break;
           if (i==7) return;
               //    if (j==7) continue;
      //    if (j==7) break;
      //    if (j==7) return;
     Console.Write(i);
     Console.Write(j);
    }
   Console.WriteLine();
   }
   Console.WriteLine("This is the end.");
   }
 }
}

if (i==7) continue;
if (i==7) break;
以上两句的执行结果相同,7开头的一行为空行。说明break语句只能跳出一层循环语句。

 if (i==7) return;
输出0至6开头的7行。程序执行结束,跳过后面的所有语句

if (j==7) continue;
缺少j为7的一列


if (j==7) break;
每一列只输出到j为6。说明break语句只能跳出一层循环语句。

 if (j==7) return;
输出0开头的一行到“06”的部分程序执行结束,跳过后面的所有语句

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3