我收到错误IndexOutOfRangeException

时间:2017-02-20 10:28:13

标签: c#

我是新来的,请帮帮我。代码正在运行但之后,分析器没有打印任何内容并给出IndexOutOfRangeException的错误。

class Program
    {
        static void Main(string[] args)
        {
            string brd = board();
            string[] sub = subjects();
            Console.WriteLine(brd);
            Console.WriteLine(sub);
            Console.ReadLine();
        }
        public static string board()
        {
            Console.WriteLine("Please Enter Board Name ");
            string Board = Console.ReadLine();
            return Board;
        }
        public static string[] subjects()
        {
            Console.WriteLine("Please Enter How many Subject Do you Want to input");
            int limit = System.Convert.ToInt32(Console.ReadLine());
            string[] Subjects = new string[limit];
            string[] index = new string[limit];
            for (limit = 1; limit <= index.Length; limit++)
            {
                Console.WriteLine("Please Enter Subject Name " + limit );
                Subjects[limit] = Console.ReadLine();
            }
            return Subjects;
        }
           }

2 个答案:

答案 0 :(得分:2)

改变这个:

for (limit = 1; limit <= index.Length; limit++)

到此:

for (limit = 1; limit < index.Length; limit++) // <= to <

索引始终低于Length,因为索引从0开始(而非1)。在您的情况下,它可以等于Length

另外,你从第二个元素开始。从头开始:

for (limit = 0; limit < index.Length; limit++) //limit = 0

答案 1 :(得分:0)

数组的索引为0,因此要访问的第一个项目为0

你的for循环应该从0开始。

e.g。代码中的for循环应该如下所示。

for (limit = 0; limit < index.Length; limit++)