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】