我的守则
static int IntCheck(string num)
{
int value;
if (!int.TryParse(num, out value))
{
Console.WriteLine("I am sorry, I thought I said integer, let me check...");
Console.WriteLine("Checking...");
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Yup, I did, please try that again, this time with an integer");
int NewValue = IntCheck(Console.ReadLine());
}
else
{
int NewValue = value;
}
return NewValue;
}
Run Code Online (Sandbox Code Playgroud)
错误
当前上下文中不存在名称"NewValue"(第33行)
你需要在外面宣布它
static int IntCheck(string num)
{
int value;
int NewValue;
if (!int.TryParse(num, out value))
{
Console.WriteLine("I am sorry, I thought I said integer, let me check...");
Console.WriteLine("Checking...");
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Yup, I did, please try that again, this time with an integer");
NewValue = IntCheck(Console.ReadLine());
}
else
{
NewValue = value;
}
return NewValue;
}
Run Code Online (Sandbox Code Playgroud)
NewValue位于if
和else
块内.您需要在块外移动声明.
static int IntCheck(string num)
{
int value;
int NewValue;
if (!int.TryParse(num, out value))
{
Console.WriteLine("I am sorry, I thought I said integer, let me check...");
Console.WriteLine("Checking...");
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Yup, I did, please try that again, this time with an integer");
NewValue = IntCheck(Console.ReadLine());
}
else
{
NewValue = value;
}
return NewValue;
}
Run Code Online (Sandbox Code Playgroud)