如何制作两列列表



因此,目前我有一项作业,输入学生的姓名和成绩,并创建一个2列列表,其中每个姓名与成绩配对。目前,我在创建列表时遇到了问题,它只打印出一个学生和一个成绩。我创建了一个26大小的数组,但只使用了5来测试它并节省时间。这是代码

static void Main(string[] args)
{
Console.WriteLine("Welcome to the grade book input the student and grades n");
string[] students = new string[26];
string names = "";
int grd = 0;
Console.WriteLine("Names tt Grades");
for (int inc = 1; inc <= 26; inc+=2)
{
Console.WriteLine("Please enter the names");
for (int x = 1; x <= 5; x++)
{
names = Console.ReadLine();
students[x] = names;
}
Console.WriteLine("Please enter the grades");
bool valid;
for (int scr = 1; scr <= 5; scr++)
{
do
{
valid = int.TryParse(Console.ReadLine(), out grd);
if (!valid || grd > 100 || grd < 0)
Console.WriteLine("Please enter a grade between 0-100");
else
Console.WriteLine("Your grade is {0}", grd);
} while (!valid || grd > 100 || grd < 0);
}
Console.WriteLine(names + "tt {0}", grd);
}

要打印所需的所有内容,需要循环遍历名称和等级数组,如下所示。您还应该使用数组的索引0,否则在尝试将第26项放入数组时会遇到问题。

Console.WriteLine("Welcome to the grade book input the student and grades n");
string[] students = new string[26];
int[] grades = new int[26]; // make an array for the grades
string names = "";
int grd = 0;
Console.WriteLine("Names tt Grades");
Console.WriteLine("Please enter the names");
for (int x = 0; x < 5; x++) // start at index 0 and go to index 4, arrays start with index 0
{
names = Console.ReadLine();
students[x] = names;
}
Console.WriteLine("Please enter the grades");
bool valid;
for (int scr = 0; scr < 5; scr++)
{
do
{
valid = int.TryParse(Console.ReadLine(), out grd);
if (!valid || grd > 100 || grd < 0)
Console.WriteLine("Please enter a grade between 0-100");
else
Console.WriteLine("Your grade is {0}", grd);
} while (!valid || grd > 100 || grd < 0);
grades[src] = grd; // save the valid grade in the grades array
}
// to print the names and grades you must loop through each index of the array
for (int i = 0; i < 5; i++)
{
// EDIT: need to access the students array here 
Console.WriteLine("{0}tt{1}", students[i], grades[i]);
}

最新更新