Skip to main content
 首页 » 编程设计

c#之数组不显示在消息框中之C#

2024年02月05日10JustinYoung

我试图在一个数组中显示 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"); 
    } 

请您参考如下方法:

你在这个循环中覆盖 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"; 
}