Adam Higgins
Adam Higgins

Reputation: 754

Integer validation method

I have this question from a test paper that im having trouble with:

Write the body of code for the method

public static int enter_No_Of_Items(int min, int max)

which will allow the user to enter a value for the number of items bought.

The value should be validated in the range min to max. Your answer should include data declaration, prompt and input statements, range check, error message control.

It might just be me but the question seems silly because I would think that validation would return true or false rather than an integer, if someone could help me answer this or explain exactly what the question wants that would be great, any help is appreciated.

Upvotes: 0

Views: 283

Answers (2)

Adam Higgins
Adam Higgins

Reputation: 754

I had a go at writing the method and this is the best I could come up with:

public static int enter_No_Of_Items(int min, int max)
    {
        string input = "input";
        bool ok = false;
        while (ok == false)
        {
            Console.WriteLine("Enter a number between {0} and {1}.", min, max);
            input = Console.ReadLine();

            if ((int.Parse(input) >= min) && (int.Parse(input) <= max))
            {
                Console.WriteLine("Valid number.");
                break;
            }

            Console.WriteLine("Invalid number.");
        }

        return int.Parse(input);
    }

    static void Main(string[] args)
    {
        int randomA = 5;
        int randomB = 9;

        int itemCount = enter_No_Of_Items(randomA, randomB);
        Console.ReadLine();
    }

If i could get feedback on how to improve it, that would be great. Thanks.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156938

You are right. Generally a validation:

  • returns a bool indicating good or wrong;
  • doesn't have a return value and throws an exception if invalid.

However, in this case, you are asked to 'ask the user' to enter a value. The scope of your method isn't only validation, it is retrieving input too. That is probably the return value expected.

You can either throw an exception if the number entered is invalid, or just keep asking until they finally enter a valid number.

Upvotes: 2

Related Questions