c#索引超出了数组错误消息的范围

时间:2018-11-05 10:30:31

标签: c#

我正在做一个需要使用方法和数组的作业。我找到了这个示例Error : Index was outside the bounds of the array.。但这并不能解决我的问题,因为数组的长度为5,并且我确保循环仅在索引小于5时重复或增加循环。

我们应该创建一个简单的程序,该程序允许用户在“收费栏”出现之前输入一定数量的成绩,或者输入999完成,然后输出排序的条目。我不断收到“数组索引超出范围”错误。现在,代码感到肿,我在清理代码和查找逻辑错误时遇到了麻烦。主要方法如下:

static void Main(string[] args)
        {
            const int maxInput = 5;
            int studentNum = 0;
            int[] studentGrades = new int[maxInput];

            // Call EnterGrades
            studentNum = EnterGrades(studentGrades, maxInput);
            if (studentNum != 0)
            {
                // Call SortGradesDescending
                SortGradesDescending(studentGrades, studentNum);
                // Call DisplayArray
                DisplayArray(studentGrades, studentNum);
            }
        }

我最紧迫的问题是EnterGrades方法。运行此版本会导致索引超出数组错误范围:

static int EnterGrades(int[] grades, int max)
        {
            int count = 0;

            do
            {
                Console.Write("Enter a student grade (or 999 to quit): ");
                grades[count] = int.Parse(Console.ReadLine());
                while ((grades[count] < 0) || (grades[count] > 100) && (grades[count] != 999))
                {
                    Console.WriteLine("Invalid input value. Please enter a value between 0 and 100.");
                    Console.Write("Enter a student grade (or 999 to quit): ");
                    grades[count] = int.Parse(Console.ReadLine());
                }
                if ((grades[count] != 999) && (count < max))
                {
                    count++;
                }
                else if (grades[count] == 999)
                {
                    grades[count] = 0;
                    break;
                }
            } while ((grades[count] != 999) && (count < max));

            if (count == max)
            {
                Console.WriteLine($"This free edition supports a maximum of {max} grades.");
                Console.WriteLine("Please upgrade to the full edition for unlimited number of grades.");
            }

            return count;
        }

但是,当我将do / while语句更改为此时,不会发生此类错误,但是它仅允许4个输入并将第5个输出为零:

do
{
    //code
} while ((grades[count] != 999) && (count < (max - 1)));

0 个答案:

没有答案