检测当跳出循环时

4

请问有人可以帮忙吗?我遇到了一个问题,如何检测当由于无效值而退出循环时。

例如,如果有人输入3 5 6 7 9作为儿童的年龄,那么这是可以的。但如果输入o 3 5 6 7,则我的代码将返回-1并退出循环。

我该如何检测并返回信息呢?

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

所以我想要做类似的事情

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

希望有人可以帮忙,因为我脑子一片空白。
乔治

嗨 @George,你试过使用调试器了吗?Visual Studio有一个很棒的调试器。 - Nahum
你能不能将 checkAgeOfChildren 声明为全局变量,在循环结束后检查它的值呢? - Jurgen Camilleri
if(!string.IsNullOrEmpty(problem)) - Stephan Bauer
你可以在循环中抛出异常,或者设置一个布尔标志,在循环后进行检查,或者直接使用checkAgeOfChildren作为标志(只需检查它是否为-1)。 - Matthew Watson
你不想在处理过程中使用Try,然后捕获错误吗? - mfdoran
5个回答

6
简单来说,你已经自己给出了答案:
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;
}

或者你抛出一个 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;
}

事实上,您似乎使用了某种整数验证。使用异常处理,Int32类已经覆盖了这一点:http://msdn.microsoft.com/en-us/library/system.int32.parse%28v=vs.71%29.aspx 如果您的验证代码没有额外的功能,那么您的代码实际上会更短:
try {
    foreach (var splitAgeOfChild in splitNumberOfChildren) {
          splitChildrensAge           = splitAgeOfChild;
          checkAgeOfChildren          = Int32.Parse(splitChildrensAge);
    }
} catch (FormatException e) {
    ViewBag.Message = problem;
}

嗨,巴特,我想我已经盯着屏幕看太久了,我选择了bool,因为我快要开始了,谢谢。现在我要休息一下。 - George Phillipson
1
经常休息能带来最好的创意。祝你好运;-)。 - Bart Friederichs

2

你可以抛出异常(取决于你的程序设计),也可以设置一个标志位。

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

或者使用异常(我这里使用了ArgumentOutOfRangeException,但您也可以创建自己的):

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

一个异常解决方案的例子会很好。我认为在这里使用异常会很合适。 - Erik van Brakel

1

为什么不在结尾处检查string.Empty?只有当出现错误时才会设置它:

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

1

只需要这样做:

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

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

您可以抛出一个异常:
try { 
   if (checkAgeOfChildren == -1)
   {
      throw new ArgumentException("Invalid Argument");
   }  catch (ArgumentException e) 
   {
       ViewBag.Message = e.Message;
   }
}

ArgumentException 可以被更合适或自定义的异常所替代。


1
为什么不在循环内这样写:
 if (checkAgeOfChildren == -1)
                {
                    ViewBag.Message  = "problem with age, stop checking";
                    break;
                }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接