//the code
parseAttempt = while (KeyBoardInput, out Response);
问问题
1535 次
1 回答
6
您不能用 while 循环替换 int.TryParse
,但可以将其与while 循环一起使用,如下所示:
string keyboardInput = Console.ReadLine();
int response;
while (!int.TryParse(keyboardInput, out response)) {
Console.WriteLine("Invalid input, try again.");
keyboardInput = Console.ReadLine();
}
另一种方法是将代码重构为单独的方法:
int readIntFromConsole()
{
while (true)
{
string keyboardInput = Console.ReadLine();
int result;
if (int.TryParse(keyboardInput, out result))
{
return result;
}
else
{
Console.WriteLine("Invalid input, try again.");
}
}
}
于 2012-08-26T11:28:45.823 回答