簡體   English   中英

我的部分數組不斷添加空數據 C#

[英]My partial array keeps adding the empty data C#

我是 C# 的新手,我們需要創建一個可以容納 100 個分數的數組。 但它還需要接受較小的內容(數字在 0-100 之間的 txt 文件)。 我的問題是,即使我添加了一個有 50 個分數的 txt 文件,它也會認為還有另外 50 個“空白分數”,它會將這些分數計為 0。所以當我的代碼執行平均分、總分和最低分時,它會搞砸的。 我的教科書對答案沒有太大幫助。

    private double Total(double[] iArray)
    {
        double total = 0;
        total = iArray.Length;

        return total;
    }
    
    //Average test score 
    private double Average(double[] iArray)
    {
        double total = 0;
        double average;
        for (int index = 0; index < iArray.Length; index++)
        {
            total += iArray[index];//look into later 
        }
        average = (double)total / iArray.Length;
        return average;
    } //done

    //for hightest test score
    private double Highest(double[] iArray)
    {
        double highest = iArray[0];
        for (int index = 1; index < iArray.Length; index++)
        {
            if (iArray[index] > highest)
            {
                highest = iArray[index];
            }
        }
        return highest;

    } //done

    private double Lowest(double[] iArray)
    {
        double lowest = iArray[0];
        for (int index = 1; index < iArray.Length; index++)
        {
            if (iArray[index] < lowest)
            {
                lowest = iArray[index];
            }
        }

        return lowest;
    }//done

    private void addFileButton_Click(object sender, EventArgs e)
    {
        try
        {
            const int SIZE = 100;               //number of test 
            double[] scores = new Double[SIZE]; //array of the test scores
            int index = 0; //loop counter
            int count = 0;
            double highestScore;
            double lowestScore;
            double averageScore;
            double totalScore;

            //Asking user to open a file
            StreamReader inputFile;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                inputFile = File.OpenText(openFile.FileName);
                
                while (!inputFile.EndOfStream && count < scores.Length)//switching index to count
                {
                    scores[count] = int.Parse(inputFile.ReadLine());
                    count++;
                }

                inputFile.Close();

            }
            else
            {
                MessageBox.Show("Operation Canceled.");
            }

            

            //Display test scores
            for (index = 0; index < count; index++)
            {
                scoreListBox.Items.Add(scores[index].ToString());
            }
            


            //grabbing information 
            highestScore = Highest(scores);
            lowestScore = Lowest(scores);
            averageScore = Average(scores);
            totalScore = Total(scores);


            //display values 
            highesScoreLabel.Text = highestScore.ToString();
            lowestScoreLabel.Text = lowestScore.ToString();
            averageTestScoreLabel.Text = averageScore.ToString();
            totalTestScoresLabel.Text = totalScore.ToString();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        
    }

您可能只需要使用Array.Resize然后:

while (!inputFile.EndOfStream && scores.Count <= SIZE)
{
    scores.Add(int.Parse(inputFile.ReadLine()));
    count++;
}
Array.Resize(scores, count);

看看這是否有效。


這是在 OP 的評論澄清應該專門使用數組之前提出的:

如果您在收集分數時使用List<double> ,然后在將其傳遞給其他方法之前使用.ToArray()怎么辦?

const int SIZE = 100;
List<double> scores = new List<double>();

[...]

if (openFile.ShowDialog() == DialogResult.OK)
{
    inputFile = File.OpenText(openFile.FileName);
    
    while (!inputFile.EndOfStream && scores.Count <= SIZE)
    {
        scores.Add(int.Parse(inputFile.ReadLine()));
        count++;
    }

    [...]

var arrScores = scores.ToArray();

//grabbing information 
highestScore = Highest(arrScores);
lowestScore = Lowest(arrScores);
averageScore = Average(arrScores);
totalScore = Total(arrScores);

請注意, while循環的條件已更改為scores.Count <= SIZE仍然只允許最多 100 個分數。

我建議您不要自己構建數組並實現所有這些方法,而是閱讀 LINQ。 LINQ 代表 Language INtegrated Query,本質上是IEnumerable<T>上的一組擴展方法,可提供您在此處需要的所有功能。

我重寫了您的事件處理程序以使用 LINQ 並且它變得更加簡單。

private void addFileButton_Click(object sender, EventArgs e)
{
    try
    {
        // Easier to follow if we just exit early
        if (openFile.ShowDialog() != DialogResult.OK)
        {
            MessageBox.Show("Operation Canceled.");
            return;
        }
        
        var scores = File.ReadAllLines(openFile.FileName)
            // Always use TryParse to avoid exceptions
            .Select(l => int.TryParse(l, out var score) ? score : -1)
            // Filter out everything that is no valid score
            .Where(s => s >= 0)
            // You could also use ToList() here for a possible minimal performance gain and the possibility to add items later.
            .ToArray();

        // Display test scores
        // We are using foreach instead of for here because we do not care about indexes. We simply want to add each item.
        // We also do not need to add the ToString(), just adding an int is fine.
        foreach (var score in scores)
            scoreListBox.Items.Add(score);

        // grabbing information 
        // We use LINQ methods here. Microsoft was nice enough di implement a bunch of often used methods on collections for us.
        var highestScore = scores.Max();
        var lowestScore = scores.Min();
        var averageScore = scores.Average();
        var totalScore = scores.Sum();


        //display values 
        highesScoreLabel.Text = highestScore.ToString();
        lowestScoreLabel.Text = lowestScore.ToString();
        averageTestScoreLabel.Text = averageScore.ToString();
        totalTestScoresLabel.Text = totalScore.ToString();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM