我有以下程序:
bool boolFlag=true;
uint length;
Console.WriteLine("Give me the length of array a:");
if (boolFlag=UInt32.TryParse(Console.ReadLine(), out length))
{
int[] a = new int[length];
Console.WriteLine("Give me {0} int numbers for array a[] :", a.Length);
for (int i = 0; i < a.Length; i++)
{
if (boolFlag = Int32.TryParse(Console.ReadLine(), out a[i]))
{
continue;
}
else
{
Console.WriteLine("Parsing at Index a[{0}] failed.", i);
}
}
}
else
{
Console.WriteLine("Could not parse length.");
}
Console.WriteLine("Give me the length of array b:");
if (boolFlag = UInt32.TryParse(Console.ReadLine(), out length))
{
int[] b = new int[length];
Console.WriteLine("Give me {0} int numbers for array b[] :", b.Length);
for (int i = 0; i < b.Length; i++)
{
if (boolFlag = Int32.TryParse(Console.ReadLine(), out b[i]))
{
continue;
}
else
{
Console.WriteLine("Parsing at Index b[{0}] failed.", i);
}
}
}
else
{
Console.WriteLine("Could not parse length.");
}
if (a.Length==b.Length)
//{
// Console.WriteLine("a and b have equal Length");
// for (int i = 0; i < a.Length; i++)
// {
// if (a[i]==b[i])
// {
// boolFlag = true;
// continue;
// }
// else
// {
// Console.WriteLine("a[{0}] != b[{0}]", i);
// }
// }
//}
//else
//{
// Console.WriteLine("The arrays don`t have equal length");
//}
Console.ReadLine();
当我进入比较部分时,我得到:
错误1名称'a'在当前上下文中不存在
错误2名称'b'在当前上下文中不存在
为什么会发生这种情况?
我的第二次尝试更改代码...声明数组超出语句范围:
int[] a;
int[] b;
bool boolFlag=true;
uint length;
Console.WriteLine("Give me the length of array a:");
if (boolFlag=UInt32.TryParse(Console.ReadLine(), out length))
{
a = new int[length];
Console.WriteLine("Give me {0} int numbers for array a[] :", a.Length);
for (int i = 0; i < a.Length; i++)
{
if (boolFlag = Int32.TryParse(Console.ReadLine(), out a[i]))
{
continue;
}
else
{
Console.WriteLine("Parsing at Index a[{0}] failed.", i);
}
}
}
else
{
Console.WriteLine("Could not parse length.");
}
Console.WriteLine("Give me the length of array b:");
if (boolFlag = UInt32.TryParse(Console.ReadLine(), out length))
{
b = new int[length];
Console.WriteLine("Give me {0} int numbers for array b[] :", b.Length);
for (int i = 0; i < b.Length; i++)
{
if (boolFlag = Int32.TryParse(Console.ReadLine(), out b[i]))
{
continue;
}
else
{
Console.WriteLine("Parsing at Index b[{0}] failed.", i);
}
}
}
else
{
Console.WriteLine("Could not parse length.");
}
if (a.Length==b.Length)
{
// Console.WriteLine("a and b have equal Length");
// for (int i = 0; i < a.Length; i++)
// {
// if (a[i]==b[i])
// {
// boolFlag = true;
// continue;
// }
// else
// {
// Console.WriteLine("a[{0}] != b[{0}]", i);
// }
// }
}
else
{
// Console.WriteLine("The arrays don`t have equal length");
}
Console.ReadLine();
现在我得到:
错误1使用未分配的局部变量'b'
错误2使用未分配的局部变量'a'
因为您正在使用a
并且b
不在其范围内。将它们的声明移到代码的开头,然后将其分配给null
。请注意,当用户输入错误的长度时,您可能要考虑停止执行。return;
显示错误消息后放置。
此外,考虑检查出这个关于变量的作用域有用的文章。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句