在 C# 中一次填充两个数组



我在从do-while循环内部复制数据并在循环外重复时遇到问题。这是在拆分功能期间,每个学生的考试成绩都与他/她的名字输入在同一行。如果这是一个非常简单的问题,我很抱歉,但我在任何地方都找不到如何解决它。非常感谢您的任何帮助。

    do {
        Console.Write("Enter the student's name followed by his/her score on the same line:");
        studentAndScore = Console.ReadLine();
        if (studentAndScore == "")
        {
            break;
        }
        string[] parsedInput;
        parsedInput = studentAndScore.Split();
            string student = parsedInput[0] = students[0];
            score = int.Parse(parsedInput[1]);
            score = studentScores[0];
        i++;
    } while (i<=MAX);
    Console.WriteLine("The test scores of the students are:");
    Console.WriteLine("students t scores t");
//And I need to repeat the list of student names and scores here

这行代码:

string student = parsedInput[0] = students[0];

首先将students[0]复制到parsedInput[0]中。 因此,您将丢失解析的输入。

相反,请尝试:

string student = parsedInput[0];
students[0] = student;

如果这实际上是你的意图。 在同一行代码中执行两个赋值很少是一个好主意。

很可能你真的想在索引器中使用i而不是0,就像在 parsedInput[i]students[i] 中那样。

只需创建两个列表...

var names = new List<String>();
var scores = new List<Int32>();

。将输入读入列表...

while (true)
{
    Console.Write("student/score: ");
    var input = Console.ReadLine();
    if (String.IsNullOrWhiteSpace(input))
    {
        var parts = input.Split();
        names.Add(parts[0]);
        scores.Add(Int32.Parse(parts[1]);
    }
    else
    {
         break;
    }
}

。并输出列表。

for (var i = 0; i < names.Count; i++)
{
    Console.WriteLine("{0}t{1}", names[i], scores[i]);
}

当然,还会添加很多错误处理。或者你可以使用字典,但我不太确定你得到的关于项目排序的保证。

var data = new Dictionary<String, Int32>();
while (true)
{
    Console.Write("student/score: ");
    var input = Console.ReadLine();
    if (String.IsNullOrWhiteSpace(input))
    {
        var parts = input.Split();
        data.Add(parts[0], Int32.Parse(parts[1]));
    }
    else
    {
         break;
    }
}
foreach (var entry in data)
{
    Console.WriteLine("{0}t{1}", entry.Key, entry.Value);
}

罗伯特写的是真的。此外,您不使用循环变量 i 将每个学生存储在数组的不同"插槽"中,因此您将覆盖当前在同一位置的所有内容。并且数组的声明必须在循环之外,否则它将在每次迭代中擦除它。

总结 C# 代码示例所需的更改,更正后的版本如下所示:

void Main()
{   
    int MAX = 20;
    var students = new string[MAX];
    var scores = new int[MAX];
    int i=0;
    do {
        Console.Write("Enter the student's name followed by his/her score on the same line:");
        var studentAndScore = Console.ReadLine();
        if (studentAndScore == "")
        {
            break;
        }
        string[] parsedInput = studentAndScore.Split();     
        students[i] = parsedInput[0];       
        scores[i] = int.Parse(parsedInput[1]);
        i++;
    } while (i<MAX);
    Console.WriteLine("The test scores of the students are:");
    Console.WriteLine("students t scores t");
    for(int k=0; k<i; k++) {
        Console.WriteLine("Student: {0}, Score: {1}", students[k], scores[k]);
    }
}

请注意,我在 for 语句中使用了 i 的值而不是 MAX ,因为用户可以通过输入空行来中断 do 循环。i始终包含之前输入的项目 #。

当然,此代码尚未包含任何错误处理,这在现实世界中是必需的。

最新更新