C#枚举类型用户输入验证:Try/Catch块无法捕获无效输入问题求助与解决方案
如何用try/catch捕获无效的星期输入?
我正在学习C#,目前遇到了一个棘手的问题,急需大家的帮助。我的任务是把相关语句包裹在try/catch块中,当输入无效时在控制台打印"Please enter an actual day of the week."。
我已经能借助枚举来判断用户输入是否有效,但没法捕获输入无效的情况。我在名为OneWeek的独立类中定义了枚举列表,我的初始代码如下:
Console.WriteLine("Please enter the current name of the day."); string input = Console.ReadLine(); string test = input.ToLower(); OneWeek.DaysOfTheWeek dayParse; bool inputParse = Enum.TryParse(test, out dayParse); try { if (inputParse == true) { Console.WriteLine("Thank God it's " + input); } } catch (FormatException) { Console.WriteLine("Please enter an actual day of the week."); } catch (Exception) { Console.WriteLine("Please enter an actual day of the week."); } Console.ReadLine(); return;
更新:
感谢所有回答者!我尝试了所有建议,这些建议都很有帮助,我也在相关讨论中找到了答案,你们让我今天很开心,谢谢!以下是我最终的代码,只是修改了部分变量,但目标一致:
try { Console.WriteLine("Please enter the current name of the day."); string input = Console.ReadLine(); string test = input.ToUpper(); OneWeek.DaysOfTheWeek day; if (Enum.TryParse<OneWeek.DaysOfTheWeek>(test, out day)) { Console.WriteLine("You are right! Today is " + test + "!"); } else { throw new OverflowException(); } } catch (OverflowException) { Console.WriteLine("Please enter an actual day of the week."); } Console.ReadLine(); return;
内容的提问来源于stack exchange,提问作者Chase To Be
相关产品推荐
相关产品推荐

