System.FormatException:'索引(从零开始)必须大于或等于零且小于参数列表的大小

时间:2018-06-19 15:40:09

标签: c#

namespace PersonalData
{
    class Program
    {
        class User
        {
            public string[] name = new string[5];
            public int[] age = new int[5];
        }

        static void Main(string[] args)
        {
            int i = 0;
            User u = new User();
            for (i = 0; i < 5; i++)
            {
                Console.WriteLine("Please enter your full name in all CAPS");
                u.name[i] = Console.ReadLine();
                Console.WriteLine("Please enter your age in numbers");
                u.age[i] = Convert.ToInt32(Console.ReadLine());
            }
            int j = 0;
            for (j = 0; j < 5; j++)
            {
                //System.FormatException: 'Index (zero based) must be greater than or equal to zero and less than the size of the argument list.'
                Console.WriteLine("The names are {0}, {1}, {2}, {3}, {4}.", u.name[j]);  
            }

            Console.ReadLine();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在遍历u数组,但尝试在每次迭代中(错误地)打印所有数组。每次迭代仅打印一个元素:

for (j = 0; j < 5; j++)
{
    Console.WriteLine("Name #{0:N} is {1}.", j, u.name[j]);  
}