Joshua
Joshua

Reputation: 23

C# while loop with range 0 - 5

Ii am new to c# and trying to create a validation through use of a while loop with the range from 0 - 5, my problem is that when this range is used it also accepts string characters, how can I stop this and only allow integers 0 - 5?

my code so far

   static void Main()

    {
        int Rateing1, Rateing2;

         Console.Write("Please rate from 0 - 5:   ");
         Rateing1 = valid_rating();

         Console.Write("\nPlease rate from 0 - 5:    ");
         Rateing2 = valid_rating();

         Console.WriteLine("\nRateing1 is {0}", Rateing1);
         Console.WriteLine("Rateing2 is {0}", Rateing2);
     }

    static int valid_rating()

          {
            int rating;

            int.TryParse(Console.ReadLine(), out rating);
                while (rating < 0 || rating > 5)
                     {
                       Console.Write("\nInvalid Input, please input an integer from 0 - 5");
                       Console.Write("\nPlease enter new rating:   ");
                       int.TryParse(Console.ReadLine(), out rating);
                     } 
            return rating;
          }

Upvotes: 2

Views: 4982

Answers (1)

Dan Tao
Dan Tao

Reputation: 128307

Change your loop to this:

while (!int.TryParse(Console.ReadLine(), out rating) || rating < 0 || rating > 5)
{
    Console.WriteLine();
    Console.WriteLine("Invalid Input, please input an integer from 0 - 5");
    Console.Write("Please enter new rating:   ");
}

That is, you want the user to enter input again if any of the following is true:

  • They entered an invalid number.
  • The number they entered is less than 0.
  • The number they entered is greater than 5.

Your problem was that you were not using the value returned by int.TryParse (which is a bool indicating success or failure); you were simply using the value written to rating which, in the case of failure, is 0 (and !(0 < 0)).

Upvotes: 4

Related Questions