首页 > 解决方案 > 在不退出循环 C# 的情况下验证来自控制台的输入值

问题描述

假设对于控制台应用程序,我希望用户输入他想扔多少个骰子。Onlu 值 1-5 将被接受。我试过这样做:

Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(true)
{
 if(amount < 1 || amount > 5)
 {
     Console.WriteLine("Please enter a value between 1-5");
     break;
 } 
}

这里的问题是,如果用户输入了一个无效的数字,程序就会停止。我希望它继续询问,直到输入正确的值。有任何想法吗?

干杯。

标签: c#validationconsole

解决方案


我还没有测试它,但稍微重构了你的代码如下,它应该做你想要的:

Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(amount < 1 || amount > 5)
{
    Console.WriteLine("Please enter a value between 1-5");
    amount = Convert.ToInt32(Console.ReadLine());
}

编辑:如果你想安全地检查它是否是一个整数值,你可以使用以下版本的代码:

    Console.WriteLine("How many dices would you like to throw?");
    var input = Console.ReadLine();

    while(!int.TryParse(input, out int amount) || amount < 1 || amount > 5)
    {
        Console.WriteLine("Please enter a value between 1-5");
        input = Console.ReadLine();
    }

推荐阅读