C# while 循环范围为 0 - 5
我是 C# 新手,尝试通过使用范围为 0 - 5 的 while 循环来创建验证,我的问题是,当使用此范围时,它也接受字符串字符,我如何才能停止此操作并只允许整数 0 - 5?
到目前为止我的代码
static void Main()
{
int Rateing1, Rateing2;
Console.Write("Please rate from 0 - 5: ");
Rateing1 = valid_rating();
Console.Write("\nPlease rate from 0 - 5: ");
Rateing2 = valid_rating();
Console.WriteLine("\nRateing1 is {0}", Rateing1);
Console.WriteLine("Rateing2 is {0}", Rateing2);
}
static int valid_rating()
{
int rating;
int.TryParse(Console.ReadLine(), out rating);
while (rating < 0 || rating > 5)
{
Console.Write("\nInvalid Input, please input an integer from 0 - 5");
Console.Write("\nPlease enter new rating: ");
int.TryParse(Console.ReadLine(), out rating);
}
return rating;
}
Ii am new to c# and trying to create a validation through use of a while loop with the range from 0 - 5, my problem is that when this range is used it also accepts string characters, how can I stop this and only allow integers 0 - 5?
my code so far
static void Main()
{
int Rateing1, Rateing2;
Console.Write("Please rate from 0 - 5: ");
Rateing1 = valid_rating();
Console.Write("\nPlease rate from 0 - 5: ");
Rateing2 = valid_rating();
Console.WriteLine("\nRateing1 is {0}", Rateing1);
Console.WriteLine("Rateing2 is {0}", Rateing2);
}
static int valid_rating()
{
int rating;
int.TryParse(Console.ReadLine(), out rating);
while (rating < 0 || rating > 5)
{
Console.Write("\nInvalid Input, please input an integer from 0 - 5");
Console.Write("\nPlease enter new rating: ");
int.TryParse(Console.ReadLine(), out rating);
}
return rating;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将循环更改为:
也就是说,如果以下任一情况为真,您希望用户再次输入内容:
您的问题是您没有使用
int.TryParse
返回的值(这是一个bool
code> 表示成功或失败);您只是使用写入rating
的值,在失败的情况下,该值是 0(以及!(0 <0)
)。Change your loop to this:
That is, you want the user to enter input again if any of the following is true:
Your problem was that you were not using the value returned by
int.TryParse
(which is abool
indicating success or failure); you were simply using the value written torating
which, in the case of failure, is 0 (and!(0 < 0)
).