我正在尝试在数组中显示5个分数,但不幸的是,我在消息框中输入的结果为0。
任何帮助都将不胜感激。
public partial class Form1 : Form
{
private int[] scoresArray = new int[5];
private int scoreTotal = 0;
private int scoreCount = 0;
public Form1()
{
InitializeComponent();
}
单击添加按钮时,分数最多可存储在阵列中5次。
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtScore.Text == "")
{
MessageBox.Show("Score is required", "Entry Error");
}
else
{
int score = Convert.ToInt32(txtScore.Text);
decimal average = 0;
if (score >= 0 && score <= 100)
{
if (scoreCount != 4)
{
scoreTotal += score;
scoresArray[scoreCount] = score;
scoreCount++;
average = scoreTotal / scoreCount;
}
else
{
MessageBox.Show("Array is full");
}
txtScoreTotal.Text = scoreTotal.ToString();
txtScoreCount.Text = (scoreCount + 1).ToString();
txtAverage.Text = average.ToString();
}
else
{
MessageBox.Show("Score must be greater than 0 and less than or equal to 100.", "Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the Score field.", "Entry Error");
}
txtScore.Focus();
}
private void btnDisplayScores_Click(object sender, EventArgs e)
{
string message = "";
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
MessageBox.Show(message, "Scores");
}
答案 0 :(得分:4)
你在这个循环中保持覆盖 message
:
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
所以它只会显示最后一个值。你可能想要追加代替它:
for (int i = 0; i < scoresArray.Length; i++)
{
message += scoresArray[i].ToString() + "\n";
}