我在分配时遇到问题,我无法清除阵列。同样在我的MessageBox中显示分数时,无论我做什么,我都会得到零作为第一个数字。我无法弄清楚要改变什么,所以零不是第一个元素。
public partial class Form1 : Form
{
int scoreTotal = 0;
int scoreCount = 0;
decimal average = 0;
int[] scoreTotalArray = new int[1];
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
Int32 score = Convert.ToInt32(txtScore.Text);
scoreTotalArray[scoreCount] = score;
Array.Resize(ref scoreTotalArray, scoreTotalArray.Length + 1);
scoreTotal += score; //accumulator
scoreCount++; //counter
average = scoreTotal / (decimal)scoreCount;//average
txtScoreCount.Text = scoreCount.ToString();//display in score count txtbox
txtScoreTotal.Text = scoreTotal.ToString(); //display in score total txtbox
txtAverage.Text = average.ToString("n2"); //display in average text box
txtScore.Clear();
txtScore.Focus();
}
}
catch (Exception ex) //catches all other exceptions
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
public bool IsValidData()
{
return
IsPresent(txtScore, "Score:") &&
IsInt32(txtScore, "Score:") &&
IsWithinRange(txtScore, "Score:", 0, 100);
}
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field, please enter a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
public bool IsInt32(TextBox textBox, string name)
{
try
{
Convert.ToInt32(textBox.Text);
return true;
}
catch (FormatException)
{
MessageBox.Show(name + "must be a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
}
public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + " must be between " + min + " and " + max + ".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
private void btnDisplayScore_Click(object sender, EventArgs e)
{
Array.Sort(scoreTotalArray);
string scoreCountString = "\n";
for(int i = 0; i < scoreCount; i++)
scoreCountString += scoreTotalArray [i] + "\n";
MessageBox.Show(scoreCountString + "\n", "Sorted Scores");
}
private void btnClearScores_Click(object sender, EventArgs e)
{
txtScore.Clear();
txtScoreTotal.Clear();
txtScoreCount.Clear();
txtAverage.Clear();
txtScore.Focus();
}
答案 0 :(得分:2)
你的int数组scoreTotalArray
总是一个元素。额外的元素包含你想要摆脱的0; - )
清除分数可以通过将数组大小调整为0来完成。
那说:您应该考虑使用List
而不是int数组。