您应该::::::很多方法可以优化你想要做的事情,但这是作业,你不想看起来像你是世界上最伟大的程序员 - 你想要做像教授期待你那样的项目。因此创建类和连接列表不属于您的特定解决方案集。尝试:
PS - 在第一个答案上,我尽量保持我的建议代码尽可能接近您的意见 - 在不更改代码的情况下回答您的问题。另一位评论者建议,不断更新文本框。文本将导致闪烁的问题。如果发生这种情况,我会建议在编辑文本时使用临时字符串。
我知道这是家庭作业 - 所以我不建议任何大的优化,这会让你看起来像你一直在做你的功课完成。
编辑您已经要求检测空白的方法。根据我对你的代码的理解,并保持它的简单,尝试:
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语句的工作找空瓶。如果您认为教授正在寻找形式(控制)验证而不是IF/THEN后面的代码隐藏,请告诉我,我会为您提供帮助。
好的 - 你提到需要排序。要做到这一点,我们需要使用某种方法来分组输入数据。我们可以使用Dictionary或class。让我们一起去上课:
把它放在一起:看看这个潜在的解决方案 - 如果你觉得它太复杂了,你的作业应该看起来像,我们可以尝试简化。告诉我:
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;
}
那么,你可以改变'nameArray'到'string.Concat(nameArray)'等。 – Fabjan
谢谢您的回复! –
您正在讨论多维数组,尽管下面的所有答案都是正确的,但这可能是您需要的最充分的答案。 https://www.dotnetperls.com/multidimensional-array或这里https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx –