首页 > 解决方案 > 将while循环放入方法中

问题描述

有没有办法将方法内部的 while 循环AddToStock放入单独的ValidateInput方法中?我也附上了ReadInteger代码。(类似于 ReadDecimal/ReadString/ReadDate)

AddToStock 代码:

private static void AddToStock()
{
    //Get item id
    int itemid = ReadInteger("\nItem ID:");

    //Confirm item id is greater than 0
    while (itemid <= 0)
    {
        Console.WriteLine("Item ID Cannot Be Less Than 1, Please Try Again");
        //Get item id
        itemid = ReadInteger("Item ID:");
    }

    //Get item name
    string itemname = ReadString("Item Name:");

    //While item name input empty
    while (string.IsNullOrWhiteSpace(itemname))
    {
        Console.WriteLine("You Didn't Enter An Item Name, Please Try Again");
        itemname = ReadString("Item Name:");
    }

    //Get item quantity
    int itemquantity = ReadInteger("Quantity:");

    //Confirm item quantity is greater than 0
    while (itemquantity <= 0)
    {
        Console.WriteLine("Quantity Cannot Be Less Than 1, Please Try Again");
        //Get item quantity
        itemquantity = ReadInteger("Quantity:");
    }

    //Get item price
    decimal itemprice = ReadDecimal("Price Paid:");

    //Confirm item price is greater than 0
    while (itemprice <= 0)
    {
        Console.WriteLine("Item Price Cannot Be Less Than Or Equal To £0.00, Please Try Again");
        //Get item price
        itemprice = ReadDecimal("Item Price:");
    }

    //Get item date added
    DateTime itemdate = ReadDate("Date Added:");
    //Add item to stock
    Employee_UI.AddToStock(itemid, itemname, itemprice, itemquantity, itemdate);
    Console.WriteLine("\nItem Added To Stock!");
}

读取整数代码:

private static int ReadInteger(string prompt)
{
    while (true)
    {
        Console.WriteLine(prompt);
        try
        {
            Console.Write("> ");
            return Convert.ToInt32(Console.ReadLine());
        }
        //If input not integer
        catch (Exception)
        {
            Console.WriteLine("Couldn't Understand That As A Number, Please Try Again");
        }
    }
}

任何帮助深表感谢!对这一切还是陌生的:)

标签: c#validation

解决方案


无需创建其他方法。您可以简单地修改您的ReadInteger方法来检查输入整数是否在范围内。

注意:与其使用Convert.ToInt32()和捕获异常,不如遵循标准的方式,即使用int.TryParse()方法。

尝试这样的事情:

private static int ReadInteger(string prompt, int minimum = int.MinValue)
{
    while (true)
    {
        Console.WriteLine(prompt);
        Console.Write("> ");

        int value;
        if (!int.TryParse(Console.ReadLine(), out value))
        {
            Console.WriteLine("Couldn't Understand That As A Number, Please Try Again");
        }
        else if (value < minimum)
        {
            Console.WriteLine($"The number Cannot Be Less Than {minimum}. Please Try Again");
        }
        else
        {
            return value;
        }
    }
}

用法:

int itemid = ReadInteger("\nItem ID:", minimum: 1);

ReadXXXX然后,您可以对其他方法遵循相同的逻辑。


推荐阅读