我的代码
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;
}
错误
名称' NewValue'在当前上下文中不存在(第33行)
答案 0 :(得分:6)
您需要在
之外声明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;
}
答案 1 :(得分:6)
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;
}