G H
G H

Reputation: 116

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.

Upvotes: 0

Views: 903

Answers (4)

SomeBody
SomeBody

Reputation: 8743

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

Upvotes: 1

iSR5
iSR5

Reputation: 3498

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

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460228

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.

Upvotes: 2

UHM
UHM

Reputation: 382

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

Upvotes: 0

Related Questions