C#console app:如何在用户输入有效数据之前继续返回错误消息?

时间:2015-10-30 15:33:56

标签: c# if-statement

我正在建立一种计算运费的方法。我已经将数据类型验证为整数。只要输入的整数大于0,逻辑就能正常工作。当输入的数字小于1时,将生成错误消息并重复请求更大的整数。好的,到目前为止。

但是,在错误消息请求有效整数后,将忽略输入的数据并且计算不正确。如何重复请求,直到用户输入大于0的数字,然后用它执行所需的计算?谢谢!

        static double CalculateShipping(int items, double shippingCharge)
        {
        if (items == 1)
            shippingCharge = 2.99;
        else if (items > 1 && items < 6)
            shippingCharge = 2.99 + 1.99 * (items - 1);
        else if (items > 5 && items < 15)
            shippingCharge = 10.95 + 1.49 * (items - 5);
        else if (items > 14)
            shippingCharge = 24.36 + 0.99 * (items - 14);
        else
        {
            Console.WriteLine("You must order at least 1 item.");
            Console.WriteLine();
            Console.Write("Please enter a whole number greater than  zero: ");
            items = Console.Read();
        }
        return shippingCharge;
    }

2 个答案:

答案 0 :(得分:1)

Console循环中包装您的While语句。有点像...

bool MyValidationFlag = false;
While MyValidationFlag == False
{
    // Prompt User

    If (UserInput is an integer > 1)
        MyValidationFlag = True
    else
        MyValidationFlag = False
}

(如果用户想要退出,您可能还想对某个“转义”值进行某种检查。)

答案 1 :(得分:1)

static int ReadItemsCountFromInput()
{
    while(true)
    {
        Console.WriteLine("enter items count: ");
        string s = Console.ReadLine();
        int r;
        if(int.TryParse(s, out r) && r > 0)
        {
            return r;
        }
        else
        {
            Console.WriteLine("you should enter number greater than zero");
        }
    }
}

static double CalculateShipping(int items, double shippingCharge)
{
        if (items == 1)
            shippingCharge = 2.99;
        else if (items > 1 && items < 6)
            shippingCharge = 2.99 + 1.99 * (items - 1);
        else if (items > 5 && items < 15)
            shippingCharge = 10.95 + 1.49 * (items - 5);
        else if (items > 14)
            shippingCharge = 24.36 + 0.99 * (items - 14);
        return shippingCharge;
}

static void Main()
{
    int items = ReadItemsCountFromInput();
    double result = CalculateShipping(items, 0);
    Console.WriteLine("Shipping: {0}", result);
}