如何使用int.TryParse避免C#程序接收非整数用户输入时崩溃
实现int.TryParse避免无效输入崩溃的修正方案
原代码核心问题
- 直接调用
Convert.ToInt32(Console.ReadLine())处理用户输入,若输入内容无法转换为int类型会直接抛出异常,导致程序崩溃 - 重复调用两次
Console.ReadLine(),需要用户连续输入两次内容才会执行后续逻辑,不符合业务需求 - 存在语法错误:
while(a == true)中a为string类型,无法直接和bool值比较 - 未处理
int.TryParse转换失败的场景,转换失败后age会被赋值为0,直接进入后续年龄判断逻辑不符合预期
修正后完整代码
using System; namespace barn_ { class Program { static void Main(string[] args) { int age; string input; do { Console.WriteLine("How old is the person?"); input = Console.ReadLine(); // 通过int.TryParse判断输入是否为合法数字 if (!int.TryParse(input, out age)) { Console.WriteLine("输入无效,请输入合法的数字年龄"); Console.WriteLine(); // 转换失败直接进入下一轮循环,要求用户重新输入 continue; } if (age >= 2 && age <= 5) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("The person has blue clothes."); Console.ResetColor(); } else if (age >= 6 && age <= 15) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("The person has red clothes."); Console.ResetColor(); } else if (age < 2) { Console.WriteLine("The person is too young."); Console.WriteLine(); } else if (age > 15) { Console.WriteLine("The person is too old."); Console.WriteLine(); } } while (age < 2 || age > 15); } } }
核心逻辑说明
int.TryParse不会抛出转换异常,会通过bool类型的返回值告知转换结果:返回true代表转换成功,转换后的int值会写入out参数age;返回false代表输入内容无法转换为int,此时直接提示用户重新输入即可- 仅调用一次
Console.ReadLine()获取用户输入,符合交互逻辑 - 额外增加
Console.ResetColor()调用,避免修改控制台颜色后后续输出一直沿用修改后的颜色 - 仅在输入为合法数字时才进入年龄范围判断逻辑,避免无效执行
内容的提问来源于stack exchange,提问作者Kromen
相关产品推荐
相关产品推荐

