您所在的位置: 首页>>读书频道>>设计开发>>.Net系列>>

3.2.2 嵌套if

http://book.51cto.com  2008-07-19 11:14  (美)米凯利斯(Michaelis, M.)著/周靖译  人民邮电出版社  我要评论(0)
  • 摘要:《C#本质论》第3章运算符和控制流,这一章将讲述运算符和控制流语句。利用运算符所提供的特定语法,可以针对计算中涉及的操作数执行各种不同的计算或操作,本小节为大家介绍嵌套if。
  • 标签:C#  本质论  运算符  控制流  C#本质论

3.2.2 嵌套if

有的时候,代码需要多个if语句。代码清单3-21首先判断用户是否通过输入一个小于或等于0的数字来选择退出,如果不是,就检查用户是否知道tic-tac-toe中的最大走棋步数。

代码清单3-21 嵌套if语句

1  class TicTacToeTrivia
2  {
3    static void Main()
4    {
5        int input;  // Declare a variable to store the input.
6
7         System.Console.Write(
8             "What is the maximum number " +
9             "of turns in tic-tac-toe?" +
10            "(Enter 0 to exit.): ");
11
12        // int.Parse() converts the ReadLine()
13        // return to an int data type.
14        input = int.Parse(System.Console.ReadLine());
15
16        if (input <= 0)
17                 // Input is less than or equal to 0.
18            System.Console.WriteLine("Exiting...");
19        else
20            if (input < 9)
21               // Input is less than 9.
22               System.Console.WriteLine(
23                  "Tic-tac-toe has more than {0}" +
24                  " maximum turns.", input);
25            else
26               if(input>9)
27                     // Input is greater than 9.
28                     System.Console.WriteLine(
29                         "Tic-tac-toe has fewer than {0}" +
30                         " maximum turns.", input);
31               else
32                      // Input equals 9.
33                      System.Console.WriteLine(
34                          "Correct, " +
35                          "tic-tac-toe has a max. of 9 turns.");
36      }
37   }

输出3-13展示了代码清单3-21的结果。

输出3-13

 What's the maximum number of turns in 
tic-tac-toe?(Enter 0 to exit.): 9
Correct, tic-tac-toe has a max. of 9 turns.

第14行在屏幕上进行提示的时候,如果用户输入9,那么程序会遵照以下执行路径前进。

(1) 第16行:检查input是否小于0。因为不是,所以跳到第20行。

(2) 第20行:检查input是否小于9。因为不是,所以跳到第26行。

(3) 第26行:检查input是否大于9。因为不是,所以跳到第33行。

(4) 第33行:显示答案正确。

代码清单3-21使用了嵌套的if语句。为了分清嵌套,代码行进行了缩进。正如在第1章学到的那样,空白不会影响执行路径。没有缩进,没有换行,代码执行起来是一样的。代码清单3-22展示了嵌套if语句的另一种形式。

代码清单3-22 if/else连贯格式化

 if (input < 0)
System.Console.WriteLine("Exiting...");
else if (input < 9)
System.Console.WriteLine(
"Tic-tac-toe has more than {0}" +
" maximum turns.", input);
else if(input>9)
System.Console.WriteLine(
"Tic-tac-toe has less than {0}" +
" maximum turns.", input);
else
System.Console.WriteLine(
"Correct, tic-tac-toe has a maximum of 9 turns.");
虽然后一种格式更常见,但在任何时候,应该选择会获得最清晰代码的一种格式。
【责任编辑:夏书 TEL:(010)68476606】

回书目   上一节   下一节
上一篇: 3.2.1 if语句 下一篇: 3.3 代码块
C#实用基础教程
C#技术开发指南
深入Vista应用程序开发
Ruby on Rails 社区网站开发
ASP.NET从入门到精通
 
 验证码: (点击刷新验证码)   匿名发表
  • Visual C++ 完全自学宝典

  • 作者:强锋科技,朱洪波
  • Visual C++ 6.0是微软公司为程序人员提供的Visual Studio 6.0工具套件中的重要组成部分。本书由浅入深地介绍使用Visual C++ 6.0..
Copyright©2005-2008 51CTO.COM 版权所有