简体   繁体   English

C# 使用 TryParse 时遇到问题

[英]C# Having trouble with TryParse

How would I add TryParse to this code, so if user enters a letter, it would tell him, "Not valid, please enter numbers only".我将如何将TryParse添加到此代码中,因此如果用户输入一个字母,它会告诉他,“无效,请仅输入数字”。 I have tried a couple of ways, but it breaks my code.我尝试了几种方法,但它破坏了我的代码。 I have tried it with for and while loops.我已经尝试过forwhile循环。 But, when I did get it to work, it only took 1 number, and then assigned that number to all my arrays.但是,当我确实让它工作时,它只需要 1 个数字,然后将该数字分配给我的所有阵列。

{
    const int SIZE = 2;

    double[] array = new double[SIZE];
    Console.WriteLine("Please Sir Enter 2 numbers");
    for (int i = 0; i < SIZE; i++)
    {
         array[i] = Convert.ToDouble(Console.ReadLine());
    }
    Console.WriteLine("===============================================");
    Console.WriteLine("The Values you've entered are");
    Console.WriteLine("{0}{1,8}", "index", "value");
    for (int counter = 0; counter< SIZE; counter++)
    {
         Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    }
    Console.WriteLine("===============================================");            
    Console.ReadLine();
}

Use the while loop inside of the for loop like this:在 for 循环中使用 while 循环,如下所示:

for (int i = 0; i < SIZE; i++)
{
   string input = Console.ReadLine();
   double num = 0;
   while(!Double.TryParse(input, out num))
   {
       Console.WriteLine("Not valid, please enter numbers only");
       input = Console.ReadLine();
   }
    array[i] = num;
}

For getting validated input from the user (especially when the type is expected to be something other than a string), I find it really useful to use a helper method.为了从用户那里获得经过验证的输入(特别是当预期类型不是字符串时),我发现使用辅助方法非常有用。

The method below takes in a string that is displayed to the user (the prompt for input), and then continues to ask the user for input until they enter a valid number ( TryParse is part of the while condition).下面的方法接受一个显示给用户的字符串(输入提示),然后继续要求用户输入,直到他们输入一个有效的数字( TryParsewhile条件的一部分)。

It also takes in an optional function parameter that can be used to validate the input, in case you want to place additional restrictions on it.它还接受一个可选的函数参数,可用于验证输入,以防您想对其施加额外限制。 The function is defined to take in a double (the user input) and return a bool ( true if the input is valid):该函数被定义为接受一个double bool (用户输入)并返回一个bool (如果输入有效则为true ):

private static double GetDoubleFromUser(string prompt, Func<double, bool> validator = null)
{
    double result;

    do
    {
        Console.Write(prompt);
    } while (!double.TryParse(Console.ReadLine(), out result) ||
             (validator != null && !validator.Invoke(result)));

    return result;
}

To use this in your code, you would just do something like:要在您的代码中使用它,您只需执行以下操作:

Console.WriteLine($"Please sir, enter {SIZE} numbers");
for (int i = 0; i < SIZE; i++)
{
    array[i] = GetDoubleFromUser($" Enter number #{i + 1}: ");
}

Output输出

上面代码示例的控制台输出图像


But other times you may want to restrict the number even further, in which case you can pass a validation method to the function.但有时您可能希望进一步限制数量,在这种情况下,您可以将验证方法传递给函数。 One simple way to do this is to pass the function as a lambda expression.一种简单的方法是将函数作为 lambda 表达式传递。 For example this expression: i => i > 10 means "return the result of the comparison if i is greater than 10 ", or in other words, "return true if i > 10 , otherwise return false ".例如这个表达式: i => i > 10表示“如果i大于10则返回比较结果”,或者换句话说,“如果i > 10则返回true ,否则返回false ”。

You could pass this to our GetDoubleFromUser method like this:您可以将其传递给我们的GetDoubleFromUser方法,如下所示:

double greaterThan10 = GetDoubleFromUser("Enter a number greater than 10: ", i => i > 10);

and now the method will keep looping while the input is not a number or the input is not greater than 10!现在,当输入不是数字或输入不大于 10 时,该方法将继续循环!

Output输出

上面代码示例的控制台输出图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM