VS2022下C#控制台应用条件语句分支跳转异常排查
问题说明
在Visual Studio 2022环境下开发小型交通类控制台应用时,程序提示用户输入1(对应“是”,需购买车票)或2(对应“否”,无需购票)后,未按预期进入路线选择流程或输出未购票提示,直接跳转返回主菜单。
原始问题代码如下:
{ Console.WriteLine("Would you like to buy a Ticket?\n"); Console.WriteLine("Please Type 1 for: Yes"); Console.WriteLine("Please Type 2 for: No"); var response = Console.ReadLine(); Console.WriteLine(response); int num = 1; if (num == 1) { Console.WriteLine("1) For the first route option, please type 1"); Console.WriteLine("2) For the second route option, please type 2"); } int num2 = 2; if (num2 == 2) { Console.WriteLine("No Ticket Purchased: Have a great day!"); } else { Console.WriteLine("Your answer was not vaild"); } }
问题原因
- 代码完全没有使用读取到的用户输入
response做逻辑判断,两个判断条件用的是硬编码赋值的固定值:num被写死为1、num2被写死为2,两个if判断永远为真,和用户实际输入没有任何关联 - 分支结构设计错误:两个if为平级独立判断,不是互斥分支,运行时会先输出路线选择提示,紧接着立刻输出未购票提示,逻辑完全冲突
- 缺少输入合法性校验:如果用户输入非数字内容,后续直接做类型转换会触发异常,导致程序直接退出返回主菜单
- 存在拼写错误:提示文本中的
vaild正确拼写为valid
修正代码
修正逻辑:移除硬编码的固定判断值,先将用户输入转换为整数,转换失败直接提示输入无效;使用if/else if/else互斥分支结构,根据用户实际输入走对应业务流程。
{ Console.WriteLine("Would you like to buy a Ticket?\n"); Console.WriteLine("Please Type 1 for: Yes"); Console.WriteLine("Please Type 2 for: No"); var response = Console.ReadLine(); Console.WriteLine(response); // 校验输入是否为合法整数,转换失败直接提示无效 if (!int.TryParse(response, out int userChoice)) { Console.WriteLine("Your answer was not valid"); return; } if (userChoice == 1) { Console.WriteLine("1) For the first route option, please type 1"); Console.WriteLine("2) For the second route option, please type 2"); // 此处可追加路线选择的输入读取、后续处理逻辑 } else if (userChoice == 2) { Console.WriteLine("No Ticket Purchased: Have a great day!"); } else { Console.WriteLine("Your answer was not valid"); } }
开发注意事项
Console.ReadLine()方法返回值为字符串类型,和数值比较前必须先做类型转换,推荐用int.TryParse做安全转换,避免转换失败触发程序崩溃- 互斥业务逻辑不要写多个平级独立if判断,使用
if/else if/else结构保证同一时间只会进入一个匹配分支 - 所有用户输入必须做合法性校验,不符合输入规则的内容要提前拦截提示,不要直接进入后续业务逻辑
内容的提问来源于stack exchange,提问作者mdemarco
相关产品推荐
相关产品推荐

