一,跳转语句
(1)break:
代码:
- 1 using System;
- 2 using System.Collections.Generic;
- 3 using System.Linq;
- 4 using System.Text;
- 5
- 6 namespace @break
- 7 {
- 8 class Program
- 9 {
- 10 static void Main(string[] args)
- 11 {
- 12 Int32 a = 0;
- 13 for(a=0;a<25;a++)
- 14 {
- 15 Console.WriteLine(a);
- 16 if (a==10)
- 17
- 18 break;
- 19
- 20
- 21 }
- 22
- 23 Console.ReadLine();
- 24 }
- 25 }
- 26 }
如果没有 break,代码从 1 一直输出到 999,但 break 的出现打断了,当 a=10 的时候,跳出输出,到 10 就中断了,只输出到 10,break 的作用就是跳出所作用区域的循环,终止作用区域的循环。
(2)continue
代码:
- 1 using System;
- 2 using System.Collections.Generic;
- 3 using System.Linq;
- 4 using System.Text;
- 5
- 6 namespace @break
- 7 {
- 8 class Program
- 9 {
- 10 static void Main(string[] args)
- 11 {
- 12 Int32 a = 0;
- 13 for(a=0;a<25;a++)
- 14 {
- 15
- 16 if (a==10)
- 17
- 18 continue;
- 19 Console.WriteLine(a);
- 20 }
- 21
- 22 Console.ReadLine();
- 23 }
- 24 }
- 25 }
这段代码输出的结果是 0---24,中间没有 10,出现 10 的时候跳出了输出 10,但是还继续进行输出 11 的循环,故输出结果没有 10.continue 的作用是当出现这个情况时,跳出这一次循环,并继续下一个循环。
二,穷举法
代码:
- 1 using System;
- 2 using System.Collections.Generic;
- 3 using System.Linq;
- 4 using System.Text;
- 5
- 6 namespace 穷举法
- 7 {
- 8 class Program
- 9 {
- 10 static void Main(string[] args)
- 11 {//100元,手套5元,袜子2元,共有几种情况
- 12 Int32 a = 0;
- 13 Int32 b = 0;
- 14 for (a = 0; a <= 20; a++)
- 15 {
- 16 for (b = 0; b <= 50; b++)
- 17 {
- 18 if ((a * 5) + (b * 2) == 100)
- 19 {
- 20 Console.WriteLine("可买" + a + "只手套," + b + "只袜子。");
- 21 }
- 22
- 23 }
- 24 }
- 25
- 26 Console.ReadLine();
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34 }
- 35 }
- 36 }
这段代码输出了买多少只袜子和手套有多少情况,分别是什么。
穷举法就是把有多少种情况都列举出来。
三,异常语句处理
try catch
代码
- 1 using System;
- 2 using System.Collections.Generic;
- 3 using System.Linq;
- 4 using System.Text;
- 5 6 namespace作业7 {
- 8 class Program 9 {
- 10 static void Main(string[] args) 11 {
- 12
- for (;;) 13 {
- Console.WriteLine("请输入数字");
- 14 15 String b = Console.ReadLine();
- 16
- try 17 {
- 18 Int32 c = Convert.ToInt32(b);
- 19 20 Console.WriteLine("输入的是数字,这次就饶了你");
- 21
- break;
- 22
- }
- 23
- catch 24 {
- 25 Console.WriteLine("输入的不是数字,重新输入!");
- 26
- }
- 27 28
- }
- 29 Console.ReadLine();
- 30
- }
- 31
- }
- 32
- }
这段代码意思是用户输入数字,输入其他提示错误,让用户重新输入,直到用户输入正确数字才会结束循环。
try{代码可能正确,也可能出现错误,如果正确,继续运行,如果错误运行 catch}
catch{try 出现错误运行这里}
finally{无论对错都会运行这里}
来源: http://www.bubuko.com/infodetail-1959903.html