vendredi 30 octobre 2015

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

Aucun commentaire:

Enregistrer un commentaire