int.TryParse校验正整数时非整数输入未触发错误的问题处理
问题原因
- 首次编写的逻辑问题:
原循环条件int.TryParse(ReadLine(), out orderQuantity) && orderQuantity > 0 == false受运算符优先级影响,实际执行逻辑是「解析成功 且 数值<=0」才进入循环,所以解析失败(比如输入非数字)时条件不成立,直接跳过循环,不会触发错误提示。 - 修改后的逻辑问题:
改为!int.TryParse(ReadLine(), out orderQuantity) && orderQuantity > 0 == false后,需要同时满足「解析失败」和「数值<=0」才进入循环。如果输入是负数,解析成功,!int.TryParse结果为false,整个条件直接返回false,不会进入循环,所以负数也无法触发错误提示。 - 额外冗余问题:
原循环体内部又调用了一次int.TryParse(ReadLine(), out orderQuantity),相当于每次循环要输入两次内容才会做判断,属于多余逻辑。
修正后代码
int orderQuantity; // 如果已经添加 using static System.Console; 可以去掉下面的Console.前缀 Console.Write("Number of Items: \t"); while (!int.TryParse(Console.ReadLine(), out orderQuantity) || orderQuantity <= 0) { Console.Write("Error: Number of Items must be a positive, whole number: \t"); }
逻辑说明
循环的触发条件是「输入解析为整数失败」或「解析成功但数值小于等于0」,只要满足任意一种情况就会继续提示用户输入,直到输入合法正整数后才会跳出循环执行后续逻辑。
内容的提问来源于stack exchange,提问作者G H
相关产品推荐
相关产品推荐

