我为 C# windows 窗体项目编写了一个事件处理程序,该项目模拟 100 次两个骰子的掷骰,并为每个掷骰返回两个骰子的总和。代码对这些总和中的每一个做了三件事,将其放在名为“rollDisplay”的 RichTextBox 中,将总和写入文本文件,并将总和添加到称为“rolls”的整数列表中。所有这些都工作正常,但现在我需要计算每个和的频率,并在 ListBox 中显示这些频率。正如下面的代码所示,我使用了 11 个不同的计数器变量和 11 个不同的字符串来添加到 ListBox。我在下面的工作,但它真的很丑陋,在我看来这是一种非常低效的方法。
我的问题是。任何人都可以提出一种更清洁的方法吗?作业要求我有 11 个单独的计数器来识别掷骰子的频率,所以我不能像其他几个问题所建议的那样使用 Linq,但我真的很不确定这是完成什么的最佳方法我需要。
private void Roll_Click(object sender, EventArgs e)
{
int roll = 0, hitTwo = 0, hitThree = 0, hitFour = 0, hitFive = 0, hitSix = 0, hitSeven = 0, hitEight = 0,
hitNine = 0, hitTen = 0, hitEleven = 0, hitTwelve = 0;
String freq1, freq2, freq3, freq4, freq5, freq6, freq7, freq8, freq9, freq10, freq11;
StreamWriter file = new StreamWriter("dicerolls.txt", true);
List<int> rolls = new List<int>();
for (int i = 0; i < 100; i++)
{
dieUno.setSide(dieUno.roll());
dieDuo.setSide(dieDuo.roll());
int diceTotal = dieUno.getSide() + dieDuo.getSide();
rolls.Add(diceTotal);
rollDisplay.AppendText(diceTotal.ToString() + "\u2028");
try
{
file.WriteLine(diceTotal.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
file.Close();
for (int i = 0; i < rolls.Count; i++)
{
roll = rolls[i];
if(roll==2)
{ hitTwo++; }
else if(roll==3)
{ hitThree++; }
else if(roll==4)
{ hitFour++; }
else if(roll==5)
{ hitFive++; }
else if(roll==6)
{ hitSix++; }
else if(roll==7)
{ hitSeven++; }
else if(roll==8)
{ hitEight++; }
else if(roll==9)
{ hitNine++; }
else if (roll == 10)
{ hitTen++; }
else if (roll == 11)
{ hitEleven++; }
else if (roll == 12)
{ hitTwelve++; }
}
freq1 = " 2 Occurs: " + hitTwo + " times"; freq2 = " 3 Occurs: " + hitThree + " times"; freq3 = " 4 Occurs: " + hitFour + " times";
freq4 = " 5 Occurs: " + hitFive + " times"; freq5 = " 6 Occurs: " + hitSix + " times"; freq6 = " 7 Occurs: " + hitSeven + " times";
freq7 = " 8 Occurs: " + hitEight + " times"; freq8 = " 9 Occurs: " + hitNine + " times"; freq9 = " 10 Occurs: " + hitTen + " times";
freq10 = " 11 Occurs: " + hitEleven + " times"; freq11 = " 12 Occurs: " + hitTwelve + " times";
frequency.Items.Add(freq1); frequency.Items.Add(freq2); frequency.Items.Add(freq3); frequency.Items.Add(freq4); frequency.Items.Add(freq5);
frequency.Items.Add(freq6); frequency.Items.Add(freq7); frequency.Items.Add(freq8); frequency.Items.Add(freq9); frequency.Items.Add(freq10);
frequency.Items.Add(freq11);
}