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

问题描述

我正在编写一个基本程序来打印出学生的姓名和年级(都在数组中)。当我尝试再次打印数组时出现错误(索引超出数组范围),我知道我必须打印什么我只是不知道我应该如何保存不同的数组输入并在循环中显示它们.

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}");
        }

标签: c#arrayslistloops

解决方案


Your code doesn't compile the way it is. I will give you the benefit of doubt and presume that it was a copy-paste error. I have rectified the mistakes compile time along side the ones you faced in the below code

Your main problem was that you declared the loop variable i outside the scope of the loop, which kept it available for the next loop where you print. Your print loop had a few issues. You were using a foreach to loop over names array, but using the index i to access the names array. See my code below with inline comments

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 
    }
}

推荐阅读