Q Rice
Q Rice

Reputation: 13

C# console app: How can I continue returning an error message until user enters valid data?

I'm building a method to calculate shipping cost. I've already validated the data type to an integer. As long as the integer entered is greater than 0, the logic works correctly. When the number entered is less than one, an error message is generated and repeats the request for a larger whole integer. Okay so far.

However, after the error message asks for a valid integer, the data entered is ignored and the calculation is incorrect. How can I repeat the request until the user enters a number greater than 0 and then perform the desired calculation with it? Thanks!

        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;
    }

Upvotes: 0

Views: 219

Answers (2)

alex.b
alex.b

Reputation: 4567

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);
}

Upvotes: 1

DeadZone
DeadZone

Reputation: 1690

Wrap your Console statements in a While loop. Something like...

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

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

(You might also want to throw in some kind of check for an "escape" value in case the user wants to quit.)

Upvotes: 1

Related Questions