简体   繁体   中英

Adding items to an array using a foreach loop in C#

I am trying to do a homework assignment that requires using a foreach loop to add items to an array. I did it using a for loop but cannot figure it out with a foreach loop.

Here is what I need, just in a foreach loop instead.

for (int i = 0; i < 5; i++)
        {
            Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  studentName[i]);
            studentScore[i] = Convert.ToInt32(Console.ReadLine());
            counter = i + 1;
            accumulator += studentScore[i];
        }

Sorry if this has been asked but I could not find an answer that helped me.

You could loop through the names array using a foreach loop and read the scores as shown below

foreach(string name in studentName)
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ", name);
    studentScore[counter] = Convert.ToInt32(Console.ReadLine());                
    accumulator += studentScore[counter];
    counter++;
}

Console.WriteLine(accumulator);
Console.ReadLine();

You should have a class like:

class Student
{
    public string Name {get; set; }
    public int Score {get; set; }
}

and a foreach like:

var counter = 0;

foreach (student in studentsArray)
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  student.Name);
    student.Score = Convert.ToInt32(Console.ReadLine());
    counter++;
    accumulator += student.Score;
}

Perhaps you meant something like this:

var studentScores = new List<int>();
foreach (var student in studentName)   // note: collections really should be named plural
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  student);
    studentScores.Add(Convert.ToInt32(Console.ReadLine()));
    accumulator += studentScores.Last();
}

If you must use an array, then something like this:

var studentScores = new int[studentName.Length];    // Do not hardcode the lengths
var idx = 0;
foreach (var student in studentName)
{
    Console.Write("\tPlease enter a score for {0} <0 to 100>: ",  student);
    studentScores[idx] = Convert.ToInt32(Console.ReadLine());
    accumulator += studentScores[idx++];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM