[英]C# Clearing Array not clearing not sure why
我使用C#中的數組編寫了該程序。 這是家庭作業。 我幾乎已經在程序中編寫了所有內容,但是我堅持清除數組。 我以為我有它,但是我不知道它在哪里不起作用。
該程序非常簡單。 用戶輸入分數並點擊“添加”按鈕。 然后,用戶可以輸入更多分數(0到100之間的任何值)。 如果用戶選擇“顯示”,則程序將對輸入的分數進行排序,並在用戶按下“清除分數”按鈕時將其顯示在消息框中(完成),程序應清除分數。 我已經編寫了它來清除文本框,並且還在其中寫了“ Scores.Clear();”。 (分數是我的列表數組的名稱),然后我將焦點返回到分數輸入文本框,以便用戶可以輸入另一個分數。
我正在使用的書只是說要清除NameOfList.Clear()類型; 所以我堅持為什么不清除。 我知道不是因為如果輸入更多分數,它將添加總數而不是重新啟動。
這是我的完整程序代碼。 我的清除開始大約一半。
先感謝您。
{
public partial class frmScoreCalculator : Form
{
//declare a list array for scores
List<int> Scores = new List<int>();
//set total and average to 0
int Total = 0;
decimal Average = 0;
public frmScoreCalculator()
{
InitializeComponent();
}
//calculate the average by dividing the sum by the number of entries
private decimal CalculateAverage(int sum, int n)
{
Average = sum / n;
return Average;
}
private void frmScoreCalculator_Load(object sender, EventArgs e)
{
}
//closes the program. Escape key will also close the program
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
//clears the text boxes, clears the array, returns focus back to the score text box like a boss.
private void btnClear_Click(object sender, EventArgs e)
{
txtScore.Text = "";
txtCount.Text = "";
txtTotal.Text = "";
txtAverage.Text = "";
Scores.Clear();
txtScore.Focus();
}
//makes sure the score is within the valid range, calculates the average, adds to the number of
//scores entered, and adds to the total
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtScore.Text == string.Empty)
{
txtScore.Focus();
return;
}
int Score = int.Parse(txtScore.Text);
if (Score > 0 && Score < 100)
{
Scores.Add(Score);
Total += Score;
txtTotal.Text = Total.ToString();
txtCount.Text = Scores.Count.ToString();
Average = CalculateAverage(Total, Scores.Count);
txtAverage.Text = Average.ToString();
txtScore.Text = string.Empty;
txtScore.Focus();
}
// if number is not valid, ask user for valid number
else
{
MessageBox.Show("Please enter a number between 0 and 100.", "ENTRY ERROR, DO IT RIGHT!");
}
// returns focus to txtNumber
txtScore.Focus();
txtScore.Text = "";
}
//display button
private void btnDisplay_Click(object sender, EventArgs e)
{
//sorts the scores low to high
Scores.Sort();
//displays scores in message box
string DisplayString = "Sorted Scores :\n\n";
foreach (int i in Scores)
{
DisplayString += i.ToString() + "\n";
}
MessageBox.Show(DisplayString);
}
}
}
您需要在清除數組的同時將變量Total
歸零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.