以下是我希望程序执行的概述
所以这是我的总和方法。我使用嵌套数组循环来制作文本框。我还提出了displayTotal()
方法。
private void sumOfBonus()
{
bonusAttack = 0;
bonusMain = 0;
bonusSecondary = 0;
attackPercent = 0;
mainPercent = 0;
secondaryPercent = 0;
for (int j = 0; j < statsBonus.GetLength(0); j++)
{
switch (statsBonus.GetLength(0))
{
case 0:
for (int i = 0; i < statsBonus.GetLength(1); i++)
{
bonusAttack += Convert.ToInt32(statsBonus[j, i]);
}
totalsBefore[j].Text = bonusAttack.ToString();
break;
case 1:
for (int i = 0; i < statsBonus.GetLength(1); i++)
{
bonusMain += Convert.ToInt32(statsBonus[j, i]);
}
totalsBefore[j].Text = bonusMain.ToString();
break;
case 2:
for (int i = 0; i < statsBonus.GetLength(1); i++)
{
bonusSecondary += Convert.ToInt32(statsBonus[j, i]);
}
totalsBefore[j].Text = bonusSecondary.ToString();
break;
case 3:
for (int i = 0; i < statsBonus.GetLength(1); i++)
{
attackPercent += Convert.ToInt32(statsBonus[j, i]);
}
totalsBefore[j].Text = attackPercent.ToString();
break;
case 4:
for (int i = 0; i < statsBonus.GetLength(1); i++)
{
mainPercent += Convert.ToInt32(statsBonus[j, i]);
}
totalsBefore[j].Text = mainPercent.ToString();
break;
case 5:
for (int i = 0; i < statsBonus.GetLength(1); i++)
{
secondaryPercent += Convert.ToInt32(statsBonus[j, i]);
}
totalsBefore[j].Text = secondaryPercent.ToString();
break;
}
}
}
private void totalsBoxes()
{
// this was called in the initializer method
for (int i = 0; i < totalsBefore.Length; i++)
{
totalsBefore[i] = new System.Windows.Forms.TextBox();
this.totalsBefore[i].Location = new System.Drawing.Point(190 + 60*i, 60);
this.totalsBefore[i].Name = "totalBefore" + statsLabel[i];
this.totalsBefore[i].Size = new System.Drawing.Size(50, 20);
this.totalsBefore[i].TabIndex = i + 1;
this.totalsBefore[i].ReadOnly = true;
totalsLabel[i] = new System.Windows.Forms.Label();
this.totalsLabel[i].Location = new System.Drawing.Point(190 + 60 * i, 36);
this.totalsLabel[i].Name = "totalLabel" + i;
this.totalsLabel[i].Size = new System.Drawing.Size(55, 20);
this.totalsLabel[i].AutoSize = true;
this.totalsLabel[i].TabIndex = i + 1;
this.totalsLabel[i].Text = statsLabel[i];
totalsBefore[i].Parent = this;
this.groupBox3.Controls.Add(totalsLabel[i]);
this.groupBox3.Controls.Add(totalsBefore[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
sumofBonus();
}
然而,当我点击按钮时,结果不会显示甚至写入零。另外,如何更有效地运行sumOfBonus()
方法?
答案 0 :(得分:3)
假设你的代码和: statsBonus声明为TextBox []和totalsBefore声明为TextBox []
你根本不需要switch语句
for (int j = 0; j < statsBonus.GetLength(0); j++)
{
int sum = 0;
for (int i = 0; i < statsBonus.GetLength(1); i++)
{
sum+= Int32.Parse(statsBonus[j,i].Text);
}
totalsBefore[j].Text = sum.ToString();
}
它基本上是你自己的代码,删除了开关块。