任何人都可以请求帮助,因为我在这里遇到了一堵墙,我怎么能检测到我因为无效值而突然出现循环.
例如,如果有人为孩子输入年龄为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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我想做像这样的事情
if(error with loop == true)
{
ViewBag.Message = problem;
}
Run Code Online (Sandbox Code Playgroud)
希望有人可以提供帮助,因为我已经空白了
乔治
很简单,你已经给出了答案:
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;
}
Run Code Online (Sandbox Code Playgroud)
或者你抛出一个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;
}
Run Code Online (Sandbox Code Playgroud)
实际上,您似乎使用某种整数验证.这个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;
}
Run Code Online (Sandbox Code Playgroud)