我尝试将变量放在循环内和循环外,以便其他函数可以使用该变量,但仍然会出错。使用菜单1创建一个列表。然后,我希望能够在菜单4中打印列表和平均值。我要在菜单1上完成所有操作,只是为了查看它是否有效。但需要将其分解。 1)清单和4)显示。
bool exit = false;
do
{
Console.WriteLine("");
Console.WriteLine("1. Create age list");
Console.WriteLine("2. Add age to list");
Console.WriteLine("3. Remove age from list");
Console.WriteLine("4. Display ages and average");
Console.WriteLine("5. exit");
Console.WriteLine("");
string input = Console.ReadLine();
Console.WriteLine("");
List<int> ages = new List<int>();
int totalAges = 0;
int age;
if (input == "1")
{
//List<int> ages = new List<int>();
//int totalAges = 0;
//User Input
Console.WriteLine("How many ages do you want to enter? ");
Console.WriteLine("");
//While loop for TryParse
while (!int.TryParse(Console.ReadLine(), out totalAges))
{
Console.WriteLine("Please enter a valid number");
Console.WriteLine("");
}
while (ages.Count != totalAges)
{
// Read grade
System.Console.WriteLine("Enter Grade: ");
//int age;
while (!int.TryParse(System.Console.ReadLine(), out age))
{
System.Console.WriteLine("Please enter a valid age.");
}
ages.Add(age);
}
for (int index = 0; index < ages.Count(); index++)
{
Console.WriteLine("");
Console.WriteLine($"Age { ages[index] }");
Console.WriteLine("");
totalAges = ages.Sum();
}
double avg = 0.0;
avg = totalAges / (ages.Count);
Console.WriteLine("");
Console.WriteLine($"The average age was { avg}");
}
else if (input == "2")
{
exit = true;
}
else if (input == "3")
{
exit = true;
}
else if (input == "4")
{
for (int index = 0; index < ages.Count(); index++)
{
Console.WriteLine("");
Console.WriteLine($"Age { ages[index] }");
Console.WriteLine("");
totalAges = ages.Sum();
}
double avg = 0.0;
avg = totalAges / (ages.Count);
Console.WriteLine("");
Console.WriteLine($"The average age was { avg}");
}
else if (input == "5")
{
exit = true;
}
else
{
Console.WriteLine("How hard is it to type 1 or 2? Try again!");
}
} while (exit == false);
答案 0 :(得分:-1)
我认为在这种情况下,最好不要在方法中而是在类中声明要访问的变量。如果希望每次调用该方法时都将其重置,则可以在方法中的每个实例上实例化它。我还要做的是将if语句分解成自己的方法。这将使您拥有更多的OOP结构化代码。