读书人

关于数组的有关问题请问上

发布时间: 2012-08-31 12:55:03 作者: rapoo

关于数组的问题请教下!

C# code
            List<string> name = new List<string>();            List<int> age = new List<int>();            List<int> yuwen = new List<int>();            List<int> shuxue = new List<int>();            string yn = null;            Console.WriteLine("请录入学员信息!");            for (int i = 0; i < i + 1; i++)            {                Console.Write("姓名:");                name.Add(Console.ReadLine());                Console.Write("年龄:");                age.Add(int.Parse(Console.ReadLine()));                Console.Write("语文:");                yuwen.Add(int.Parse(Console.ReadLine()));                Console.Write("数学:");                shuxue.Add(int.Parse(Console.ReadLine()));                Console.Write("是否继续<y/n>:");                yn = Console.ReadLine();                Console.WriteLine();                if (yn.Equals("n"))                    break;            }            Console.WriteLine("--------------------循环打印数组----------");            Console.WriteLine("姓名\t年龄\t语文\t数学\t总分\t平均分");            for (int j = 0; j < name[j].Count(); j++)            {                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}"                    , name[j], age[j], yuwen[j], shuxue[j], yuwen[j] + shuxue[j], (yuwen[j] + shuxue[j]) / 2);            }

一种情况是:输入3个人的成绩,循环输出只打印一个人的成绩

另一种情况是:输入1个人的成绩,能正常输出,但是会报错


[解决办法]
这程序实在不怎么样,你的错误在于j < name[j].Count()应该是j < name.Count才对。

1. 第一个for可以用do..while代替掉;

2. 出问题的原因是扩展方法string.Count() (name[j].Count())掩盖住了逻辑错误,由于等价于name[j].Length,所以第二个for循环的次数变成依赖于姓名字符串的长度。自然就会出现结果不正确或者数组索引出界的问题。

读书人网 >C#

热点推荐