你应该::::: 有很多方法可以优化你正在尝试做的事情,但这是功课,你不想看起来像世界上最伟大的程序员——你想做教授期望你做的项目。因此,创建类和加入列表不是您特定解决方案集的一部分。试试:
PS - 在第一次回答时,我试图让我的建议代码尽可能接近您的 - 在不更改代码的情况下回答您的问题。另一位评论者建议不断更新 textbox.Text 会导致闪烁问题。如果您遇到这种情况,我建议您在编辑文本时使用临时字符串。
我知道这是功课 - 所以我不建议进行任何大优化,让您看起来像是在 SO 完成了功课。
EDIT 您要求提供一种检测空的方法。根据我对您的代码的理解并使其保持简单,请尝试:
private void AddButton_Click(object sender, EventArgs e)
{
if (this.index < 10)
{
if(nameBox.Text.Length==0||weightBox.Text.Length==0||heightBox.Text.Length==0){
MessageBox.Show("You must enter a name, weight, and height!");
}else{
nameArray[this.index] = nameBox.Text;
weightArray[this.index] = double.Parse(weightBox.Text);
heightArray[this.index] = double.Parse(heightBox.Text);
this.index++;
nameBox.Text = "";
weightBox.Text = "";
heightBox.Text = "";
}
}
}
private void ShowButton_Click(object sender, EventArgs e)
{ string myString = "";
for(int i=0;i<nameArray.Length;i++)
{
myString+= "Name: "+nameArray[i]+", ";
myString += "Weight: "+weightArray[i]+", ";
myString += "Height: "+heightArray[i]+"\n");
}
txtShow.Text = myString;
}
注意 文本框具有验证方法,可以在我修改后的编辑中完成我的 IF/THEN 语句的工作以查找空。如果您认为 prof 正在寻找表单(控件)验证而不是代码隐藏 IF/THEN,请告诉我,我会提供帮助。
好的 - 你提到了排序的必要性。为此,我们需要使用某种方式对输入数据进行分组。我们可以使用字典或类。我们一起上课吧:
把它们放在一起:看看这个潜在的解决方案 - 如果你认为它对于你的家庭作业来说太复杂了,我们可以尝试简化。让我知道:
public class Person{
public string Name {get;set;}
public double Height {get;set;}
public double Weight {get; set;}
public string Print(){
return "Name: "+Name+", Height: "+Height.ToString()+", Weight: "+Weight.ToString()+"\r\n";
}
}
Person[] People = new Person[10];
int thisIndex = 0;
private void AddButton_Click(object sender, EventArgs e)
{
if (this.index < 10)
{
if(nameBox.Text.Length==0||weightBox.Text.Length==0||heightBox.Text.Length==0)
{
MessageBox.Show("You must enter a name, weight, and height!");
}else{
Person p = new Person();
p.Name = nameBox.Text;
p.Weight = double.Parse(weightBox.Text);
p.Height = double.Parse(heightBox.Text);
People[thisIndex] = p;
thisIndex++;
nameBox.Text = "";
weightBox.Text = "";
heightBox.Text = "";
}
}
}
private void ShowButton_Click(object sender, EventArgs e)
{
People = People.OrderBy(p=>p.Name).ToArray();
string myString = "";
for(int i=0;i<10;i++)
{
if(People[I]!=null){
myString+= People[I].Print();
}
}
txtShow.Text = myString;
}