在单个foreach循环(或其他解决方案)中打印2个值

时间:2019-03-15 17:14:40

标签: c# arrays list loops

我正在编写一个基本程序,以打印出学生的姓名和年级(均按数组排列)。当我再次尝试打印数组时出现错误(索引超出数组范围),我知道要打印的内容,只是不知道如何保存不同的数组输入并循环显示它们

static void Main(string[] args)
    {
        double average = 0;
        //double Hoogste = 0;
        double sum = 0;
        int i;
        Console.Write("lesson: ");
        string lesson = Console.ReadLine();
        Console.Write("number of students: ");
        int numStudents = int.Parse(Console.ReadLine());
        Console.WriteLine("\n");
        string[] names = new string[numStudents];
        int[] grade = new int[numStudents];

        for (i = 0; i < numStudents; i++)
        {
            Console.Write("name? ");
            names[i] = Console.ReadLine();
            Console.Write("grade? ");
            grade[i] = int.Parse(Console.ReadLine());

            sum += grade[0];
            average = sum / numStudents;

        }

        foreach (string item in names) ;
        {
            Console.WriteLine($"The grade of {names[i]} is {grade[]i}");
        }

2 个答案:

答案 0 :(得分:0)

您的代码未按原样进行编译。我会给您带来疑问的好处,并假定这是一个复制粘贴错误。我已纠正您在以下代码中遇到的错误的编译时间

您的主要问题是,您在循环范围之外声明了loop variable i,这使它可用于下一个打印循环。您的打印循环有一些问题。您使用foreach遍历names数组,但是使用索引i访问names数组。请参阅下面的代码以及内嵌注释

static void Main(string[] args) {
    double average = 0;
    //double Hoogste = 0;
    double sum = 0;
    //int i; // do not declare it here, this was causing you issues

    Console.Write("lesson: ");
    string lesson = Console.ReadLine();

    Console.Write("number of students: ");
    int numStudents = int.Parse(Console.ReadLine());

    Console.WriteLine("\n");

    string[] names = new string[numStudents];
    int[] grade = new int[numStudents];

    for (int i = 0; i < numStudents; i++) { // declare the loop variable here
        Console.Write("name? ");
        names[i] = Console.ReadLine();

        Console.Write("grade? ");
        grade[i] = int.Parse(Console.ReadLine());

        sum += grade[i]; // i presume you don't want to do grade[0] but rather grade[i]
    }

    average = sum / numStudents; // I presume you don't want this line inside the for-loop, if you expect the average to be properly calculated

    //foreach (string item in names) // there was a semi-colon here by mistake, which should not be there
    for (int i = 0; i < numStudents; ++i) // you want to loop over the index
    {
        Console.WriteLine($"The grade of {names[i]} is {grade[i]}"); // i was outside the square brackets like grade[]i 
    }
}

答案 1 :(得分:0)

从两个小变化开始:

  1. 第一个for循环需要为i for (int i = 0;声明一个类型,在foreach循环中,i超出范围,因此您不会能够使用它。您可能可以删除foreach循环,而将Console.WriteLine放在第一个foreach循环的底部。

  2. 此外,使用{grade[]i}

  3. 检查语法