为什么我的数组中什么都不应该包含0-C#

时间:2019-01-27 19:09:22

标签: c# arrays

我正在为学校做一些事情,只是一个基本的分数计算器。我知道这不是最漂亮的代码,但是它可以工作,而这正是该类在开始时所关注的。

我唯一的问题是,每当我单击“显示”时,它将打印出20 0。数组的长度为20。其他一切都在工作。它将我输入的数字加到数组中并替换为0。但是除非我特别输入,否则我根本不希望它有0。

感谢您的帮助。

完整代码:

// Creates the list that displays the score
List<string> scoreList = new List<string>();

// Array to store up to 20 scores
int[] scoreArray = new int[20];

// class level variable to store current open slot in the array
int openSlot = 0;

public Form1()
{
    InitializeComponent();
}
// Initializes variables that hold our math total and count of numbers entered
int total = 0;
int count = 0;

private void btnExit_Click(object sender, System.EventArgs e)
{
    this.Close();
}

private void btnAdd_Click(object sender, System.EventArgs e)
{
    if (openSlot <= scoreArray.GetUpperBound(0))
    {
        try
        {
            // Basic math for conversion of entered number and calculating total numbers entered
            // and the averages of those numbers
            int score = Convert.ToInt32(txtScore.Text);
            total += score;
            count += 1;
            int average = total / count;
            txtScoreTotal.Text = total.ToString();
            txtScoreCount.Text = count.ToString();
            txtAverage.Text = average.ToString();
            txtScore.Focus();
        }
        catch(System.FormatException) // Makes sure that the user enters valid character into box
        {
            MessageBox.Show("Please enter valid number into box");
            return;
        }

        // Adds the most recent entered number to the Score List
            scoreList.Add(txtScore.Text);
        }

        // if statement to make sure that there is still room in the array to store the
        // new entry
        if (openSlot > scoreArray.GetUpperBound(0)) // GetUpperBound(0) returns the index of the last element in the first dimension
        {
            MessageBox.Show("The array is full! The most recent number was not added.");
            txtScore.SelectAll();
            txtScore.Focus();
            return;
        }
        // Assigns a variable as an integer from the score text box
        // to allow us to numerically sort the numbers in the scoreArray
        int scoreParse = Int32.Parse(txtScore.Text);

        // move the most recent number to the current open slot in the score array
        scoreArray[openSlot] = scoreParse;

        // add 1 to openSlot
        openSlot += 1;
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        // Clears all input fields and resets variables to 0
        openSlot = 0;
        total = 0;
        count = 0;
        txtScore.Text = "";
        txtScoreTotal.Text = "";
        txtScoreCount.Text = "";
        txtAverage.Text = "";
        txtScore.Focus();

        // Clears the array and list
        int[] clearScoreArray = new int[20];
        scoreArray = clearScoreArray;
        List<string> clearScoreList = new List<string>();
        scoreList = clearScoreList;
    }

    private void btnDisplay_Click(object sender, EventArgs e)
    {
        // If array has no stored values, display a MessageBox that informs user
        if (scoreArray == null || scoreArray.Length == 0)
        {
            MessageBox.Show("There are no numbers to display");
            return;
        }

        //move focus to the code textbox
        txtScore.Focus();

        // Creates a blank string variable named scr to input the scores into
        // for the MessageBox
        string scr = "";
        foreach (var scoreAdded in scoreArray)
        {
            // Adds variable scr as the string to display 
            scr += scoreAdded + "\n";
        }
        // Sorts the array from lowest to highest number
        Array.Sort(scoreArray);

        // Displays a message box with the scores that were added
        MessageBox.Show(scr);
    }
}

3 个答案:

答案 0 :(得分:0)

欢迎您!

最初声明一个对象时,有一个默认的初始化值。在这种情况下,0是C#中int的默认值。如果有支持的构造函数,则通常可以在对象初始化时更改默认值。

声明int[] scoreArray = new int[20];时,所有20个变量的值都分配为0。这是因为C#不允许未初始化的变量。

此链接显示C#的所有默认初始化值。

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table

答案 1 :(得分:0)

当您声明一定数量的数组(在您的位置为20)时,它们会得到某种值,通常为0。使用myArrayHere.length时请记住这一点,因为它将检查有多少个数组声明(int []数组)和初始化(... = new array []),而不修改(给定值)的数量。

最佳解决方案是,IMO正在创建一个函数,该函数将知道您需要一个数组中的元素数量或您正在使用的元素数量(只有一个函数,通过使用循环,然后稍后对其进行修改...但这是解决此问题的一种方法,比我所指出的要好得多,但是正如我所看到的,您比使用C#(问题)还新。好的代码是好的,因为您的第一个项目应该用于学习,以后,您可以对其进行改进,如果您想成为专业人士,则可以学习一些编程课程,以全面了解如何改进代码。

祝你好运! -Normantas

答案 2 :(得分:0)

如果您不希望零为默认值,则可以使用nullable。

int? [] array = new int?[20];