用于验证字符串输入并返回双输出的方法

本文关键字:输出 方法 返回 验证 字符串 输入 用于 | 更新日期: 2024-09-25 05:14:10

我想创建一个通用方法来根据ceratin规则验证用户输入。

这就是我调用该方法的方式,我得到了一个错误,因为字符串不能是双重的:

Console.Write("Input the price of the beverage : ");
string priceInput = Console.ReadLine();
double priceInputVal = ValidateBrand(priceInput);

这是我调用的方法:

private double ValidatePrice(string priceInput)
{
    bool success = true;
    double priceOutput; 
    do
    {
        bool result = Double.TryParse(priceInput, out priceOutput);
        if (result == false)
            Console.WriteLine("Please, write a valid number");
        else 
            success = false;
    } while (success);
    return priceOutput;
}

我该如何解决这个问题?我已经测试了这个方法,但这是不可能的。

如果能给出一个彻底的答案,我会很感激的,我对此还很陌生。

用于验证字符串输入并返回双输出的方法

这里的问题是,如果不能将priceInput解析为double,您将进入一个无限循环。为了避免这种情况,您可以这样更改ValidatePrice方法:

private double? ValidatePrice(string priceInput)
{
    double? priceOutput = default(double?);     
    Double.TryParse(priceInput, out priceOutput)
    return priceOutput;
}

这样称呼它:

double? priceInputVal = null;
do
{
    Console.Write("Input the price of the beverage : ");
    priceInputVal = ValidateBrand(Console.ReadLine());
    if (priceInputVal == null)
    {
        Console.WriteLine("Please, write a valid number");
    }
}
while (princeInputVal == null)