【发布时间】:2014-11-09 11:00:24
【问题描述】:
//capture input value for peak size and return
public static int GetPeakSize()
{
//declare variables, intitialize and parse after input
int peak;
Console.WriteLine("\nPlease enter the peak size (must be a number 1-10): ");
peak = int.Parse(Console.ReadLine());
//if user enter anything that is not inside the 1-10 range, default
//to 3
if (peak < 1 || peak > 10)
{
peak = 3;
}
return peak;
}
在上面的方法中,我只是尝试收集输入,解析它,如果输入不在 1-10 的范围内,则返回默认值 3。但我不只是验证数字输入,而是如果输入了除数值 1-10 之外的任何值,则希望返回默认值 3。因此,如果他们输入“四”而不是 4,我希望该值默认为 3。我希望我可以按照 if (value != int || value 10) 的方式做一些事情。 .....default = 3。我知道这不能完成,但它周围有吗?
【问题讨论】:
-
为什么不直接禁止非数字输入?如果他们输入“四”,则会显示一条消息“请仅输入数字”。用户输入“四”并让程序静默假设 3 似乎令人困惑。
-
@eddie_cat 是的,我知道,不过这是作业要求。
-
明白了,只是觉得值得注意。
标签: c# .net if-statement