Search code examples
c#while-loopintegertryparse

tryparse method for positive integer is not returning an error with inputs that are not integers


I have the following code:

int orderQuantity;

Write("Number of Items: \t");
while(int.TryParse(ReadLine(), out orderQuantity) && orderQuantity > 0 == false)
{
     Write("Error: Number of Items must be a positive, whole number: \t");
     int.TryParse(ReadLine(), out orderQuantity);
}

The goal is that while the input is not a positive integer, continue to return an error. Once the input is a positive integer, continue on.

The problem is this logic only works with the negative numbers. When I try to make the code into while(!int.TryParse(ReadLine(), out orderQuantity) && orderQuantity > 0 == false)

I run into the code not recognizing integers nor negative numbers as errors.


Solution

  • Use:

    while(!int.TryParse(ReadLine(), out orderQuantity) || orderQuantity <= 0)
    {
        Write("Error: Number of Items must be a positive, whole number: \t");
    }
    

    So you have to handle the cases that it's not a valid integer and that it's valid but not greater than zero separately. Also remove the TryParse from the loop body.