【问题标题】:Array doesn't display in the message box - C#数组不显示在消息框中 - C#
【发布时间】:2015-11-10 02:39:50
【问题描述】:

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

【问题讨论】:

    标签: c# arrays output


    【解决方案1】:

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

    【讨论】:

    • 谢谢它的工作,但现在当你不输入分数时它会显示额外的零。
    • @Benyamin:嗯,你有一个长度为 5 的数组。无论你是否更新所有 5 个值,它总是长度为 5。 0 是整数的默认值。如果集合的长度需要是动态的,您可以尝试使用 List&lt;int&gt; 之类的东西来代替数组。这样,例如,如果只输入 3 个分数,那么您可以只动态地将 3 个元素添加到集合中。
    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    相关资源
    最近更新 更多