Home > Back-end >  tryparse method for positive integer is not returning an error with inputs that are not integers
tryparse method for positive integer is not returning an error with inputs that are not integers

Time:10-22

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.

CodePudding user response:

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.

CodePudding user response:

int orderQuantity;

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

CodePudding user response:

while((!int.TryParse(ReadLine(), out orderQuantity)) || (orderQuantity <= 0))

CodePudding user response:

you need to parenthesize the condition so this :

int.TryParse(ReadLine(), out orderQuantity) && orderQuantity > 0 == false

changed to be this :

(int.TryParse(ReadLine(), out orderQuantity) && orderQuantity > 0) == false

CodePudding user response:

An extension method might help you to get code that is more expressive and thus more easy to read:

public static class StringExtensions
{
   public static bool IsPositiveInt32(this string input, out int value)
   {
      if(!int.TryParse(input, out value))
      {
         return false;
      }
      return value > 0;
   }
}

Usage will be

int orderQuantity;
Write("Number of Items: \t");
while(!ReadLine().IsPositiveInt32(out orderQuantity))
{
    Write("Error: Number of Items must be a positive, whole number: \t");
}
  • Related