【问题标题】:How do I add Student objects to an array through the use of a button?如何通过使用按钮将学生对象添加到数组中?
【发布时间】:2020-01-16 06:55:50
【问题描述】:

我尝试通过使用 for 循环将学生添加到数组中,该循环检查当前数组以确保数组中没有学生已经输入了正在输入的学生姓名。

bool found = false;

for (int i = 0; i < 3; i++)
{
    resultMessage.Text = "Hello";
    if (newStudent[i] != null)
    {
        string fullName = newStudent[counter].Name();
        if (fullName.ToUpper() == newStudent[i].Name().ToUpper())
        {
            resultMessage.Text = "Name is already in the system.";
            found = true;
        }
    }            
}
if (found == false)
{
    if (counter > 2)
    {
        resultMessage.Text = "Array is full.";
    }
    else
    {
        newStudent[counter] = new Student(StudentID.Text, FirstName.Text, MiddleInitial.Text, LastName.Text, HouseNumber.Text, Street.Text, CityCounty.Text, Country.Text,
        State.Text, ZipCode.Text, DOB.Text);
        resultMessage.Text = "Age: " + newStudent[counter].Age;
    }
}

counter++;

counter 是静态的,并在按钮代码的末尾递增。它目前不会通过newStudent[i] == null; 语句。它去了它,认为数组是空的并继续到代码的下一部分。我没有使用太多的 HTML 代码,我通过之前的代码完成了所有的功能。

【问题讨论】:

  • 您似乎在混合使用 [i][counter],这无济于事。您还可以发布更多关于newStudent 以及您如何创建它的信息吗?这似乎不是完整的代码。
  • 学生[] newStudent = 新学生[3];学生新学生A;静态 int 计数器 = 0;这在代码文件中的按钮之外。我有一个使用多个构造函数创建的 Student 类文件,其中一个是 Name,它从文本框中提取名字和姓氏。
  • “通过newStudent[i] != null; 声明”更正此部分。在你的问题中。
  • @bishopob 在按钮的代码中,您是否可以将其注释掉并将学生对象硬编码到数组中。然后在随后的点击中,确认学生存在?如果没有,那么可能是 Web 框架在每次“点击”时都在重建类,并且可能需要数组是静态的。

标签: c# asp.net arrays


【解决方案1】:

我认为你应该只在添加新学生时增加counter,当找到重复的学生或达到最大计数器时,你可以通过从按钮返回来做到这一点。

for (int i = 0; i < 3; i++)
{
    resultMessage.Text = "Hello";
    if (newStudent[i] != null)
    {
        string fullName = newStudent[counter].Name();
        if (fullName.ToUpper() == newStudent[i].Name().ToUpper())
        {
            resultMessage.Text = "Name is already in the system.";
            return;
        }
    }            
}
if (counter > 2)
{
    resultMessage.Text = "Array is full.";
    return;
}
else
{
    newStudent[counter] = new Student(StudentID.Text, FirstName.Text, MiddleInitial.Text, LastName.Text, HouseNumber.Text, Street.Text, CityCounty.Text, Country.Text,
    State.Text, ZipCode.Text, DOB.Text);
    resultMessage.Text = "Age: " + newStudent[counter].Age;
}
counter++;

【讨论】:

  • 这是我想过要做的事情,但问题在于,当我运行代码时,它不会通过 if (newStudent[i] != null) 部分到达名称检查位置的代码。
  • 为什么?这是按钮方法的第一部分。它必须到达它。
  • 我知道它最终必须达到那个点,但现在的问题是,当我运行它时,计算机认为数组中没有值并跳过那个 if 语句。
  • 确保它进入循环,并显示newStudent数组的内容。您可能会发现问题出在哪里。
  • 如果可能的话,你可以把文件发给我。
猜你喜欢
  • 2017-10-19
  • 1970-01-01
  • 2016-10-29
  • 2020-04-09
  • 2014-08-13
  • 1970-01-01
  • 2018-03-13
  • 2021-06-11
  • 1970-01-01
相关资源
最近更新 更多