C#如何实现控制台输入仅允许数字,非法输入可重输的异常校验?
C# 控制台数字输入校验实现方案
问题根因
你之前添加try catch后userInput变量无法在if语句中使用,核心是变量作用域问题:如果将int userInput声明在try代码块内部,该变量的作用范围仅限try块,块外的代码自然无法访问。
推荐实现方案
优先使用int.TryParse代替Convert.ToInt32+try catch的组合,该方法专门用于安全转换字符串为整型,无需捕获异常,性能更优,配合循环即可实现输入错误后重新输入的需求:
Console.WriteLine("Do you want to: 1. play against an Ai or 2. let two Ai´s play against each other?"); Console.WriteLine("Please choose one option!"); int userInput = 0; // 循环条件:输入解析失败 或 输入数字不在1/2范围内,就一直要求重新输入 while (!int.TryParse(Console.ReadLine(), out userInput) || userInput < 1 || userInput > 2) { Console.WriteLine("输入无效!仅允许输入数字1或2,请重新输入:"); } Console.WriteLine("\n"); if (userInput == 1) { // 玩家对战AI逻辑 Player player = new Player(); // 后续代码 } else if (userInput == 2) { // 双AI对战逻辑 }
注:如果使用C# 9及以上版本,循环条件里的
userInput < 1 || userInput > 2可以替换为更简洁的模式匹配写法userInput is not (1 or 2)。
try catch兼容写法
如果一定要用try catch实现,需要把userInput变量声明提到try块外部,示例如下:
Console.WriteLine("Do you want to: 1. play against an Ai or 2. let two Ai´s play against each other?"); Console.WriteLine("Please choose one option!"); int userInput = 0; bool inputIsValid = false; while (!inputIsValid) { try { userInput = Convert.ToInt32(Console.ReadLine()); if (userInput ==1 || userInput ==2) { inputIsValid = true; } else { Console.WriteLine("输入范围无效,请输入1或2:"); } } catch (FormatException) { Console.WriteLine("输入包含非数字内容,请重新输入:"); } catch (OverflowException) { Console.WriteLine("输入数字超出允许范围,请重新输入:"); } } // 后续可正常使用userInput Console.WriteLine("\n"); if (userInput == 1) { Player player = new Player(); // 后续代码 }
内容的提问来源于stack exchange,提问作者RedDragon2001
相关产品推荐
相关产品推荐

