George Phillipson
George Phillipson

Reputation: 93

Detect when breaking out of loop

Can anyone please help as I have run into a wall here, how can I detect when I break out of a loop due to invalid value.

For example, if someone enters the ages 3 5 6 7 9 for children that will be ok, if the enter o 3 5 6 7 this will return -1 in my code and exit the loop.

How do I detect that and return message

public static int IntIsValid(string p)
        {
            int pn;
            bool isNum = int.TryParse(p, out pn);
            int pnIsvalid = isNum ? pn : -1;
            return pnIsvalid;
        }

string addDash  = Regex.Replace(agesOfChildren, " ", "_");
            string[] splitNumberOfChildren  = addDash.Split('_');
            string splitChildrensAge        = string.Empty;
            int checkAgeOfChildren          = 0;
            string problem = string.Empty;
            foreach (var splitAgeOfChild in splitNumberOfChildren)
            {
                splitChildrensAge           = splitAgeOfChild;
                checkAgeOfChildren          = RemoveInvalidInput.IntIsValid(splitChildrensAge);
                if (checkAgeOfChildren == -1)
                {
                    problem = "problem with age, stop checking";
                    break;
                }
            }

So I would want to do soemthing like

if(error with loop == true)
{
ViewBag.Message = problem;
}

Hopefully someone can help, as I have gone blank

George

Upvotes: 4

Views: 1620

Answers (5)

Bart Friederichs
Bart Friederichs

Reputation: 33511

Simple, you already give the answer yourself:

boolean error_with_loop = false;
foreach (var splitAgeOfChild in splitNumberOfChildren) {
      splitChildrensAge           = splitAgeOfChild;
      checkAgeOfChildren          = RemoveInvalidInput.IntIsValid(splitChildrensAge);
      if (checkAgeOfChildren == -1)
      {
           error_with_loop = true;
           problem = "problem with age, stop checking";
           break;
      }
}

if (error_with_loop) {
    ViewBag.Message = problem;
}

Or you throw an Exception:

try {
    foreach (var splitAgeOfChild in splitNumberOfChildren) {
          splitChildrensAge           = splitAgeOfChild;
          checkAgeOfChildren          = RemoveInvalidInput.IntIsValid(splitChildrensAge);
          if (checkAgeOfChildren == -1)
          {
                // note: no need to break
                throw new ErrorWithLoopException();
          }
    }
} catch (ErrorWithLoopException e) {
    ViewBag.Message = problem;
}

In fact, you seem to use some kind of integer validation. The Int32 class has that covered with exceptions: http://msdn.microsoft.com/en-us/library/system.int32.parse%28v=vs.71%29.aspx Your code will actually be shorter (don't know if it is applicable, as I do not know what your validation code does extra):

try {
    foreach (var splitAgeOfChild in splitNumberOfChildren) {
          splitChildrensAge           = splitAgeOfChild;
          checkAgeOfChildren          = Int32.Parse(splitChildrensAge);
    }
} catch (FormatException e) {
    ViewBag.Message = problem;
}

Upvotes: 6

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

Why not like this inside the loop:

 if (checkAgeOfChildren == -1)
                {
                    ViewBag.Message  = "problem with age, stop checking";
                    break;
                }

Upvotes: 1

Darren
Darren

Reputation: 70718

Simply do:

if (checkAgeOfChildren == -1)
{
  problem = "problem with age, stop checking";
  break;
}

if (!string.IsNullOrEmpty(problem)) {
   ViewBag.Message = problem;
}

You can also throw an exception:

try { 
   if (checkAgeOfChildren == -1)
   {
      throw new ArgumentException("Invalid Argument");
   }  catch (ArgumentException e) 
   {
       ViewBag.Message = e.Message;
   }
}

ArgumentException can be replaced with a more suitable or custom Exception.

Upvotes: 1

Dave S
Dave S

Reputation: 1423

Why don'y you just check for string.Empty at the end? It will only be set if you have an error:

if (!string.IsNullOrEmpty(problem))
{
     ViewBag.Message = problem;
}

Upvotes: 1

keyboardP
keyboardP

Reputation: 69362

You can either throw an exception (depending on your program's design) or you can set a flag.

bool success = true;

foreach (var splitAgeOfChild in splitNumberOfChildren)
{
      splitChildrensAge = splitAgeOfChild;
      checkAgeOfChildren = RemoveInvalidInput.IntIsValid(splitChildrensAge);
      if (checkAgeOfChildren == -1)
      {
           problem = "problem with age, stop checking";
           success = false; // change the flag
           break;
      }
}

Or using an exception (I've used ArgumentOutOfRangeException here but you can create your own):

foreach (var splitAgeOfChild in splitNumberOfChildren)
{
      splitChildrensAge = splitAgeOfChild;
      checkAgeOfChildren = RemoveInvalidInput.IntIsValid(splitChildrensAge);
      if (checkAgeOfChildren == -1)
      {
           problem = "problem with age, stop checking";
           throw new ArgumentOutOfRangeException("Age", problem);
      }
}

Upvotes: 2

Related Questions