Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 82.7k

problem with index when using List<T>

Jun 18 2022 5:20 PM

Hi

This code simumates matches between 3 teams. each team plays against the two others. Winning gives 3 points, equal gives 1 point to each team. I did the same program with arrays and there i had no error, but using List<>T, I always get an error at line

points[i] += 3; or points[j] += 3;        the index is out of range or cannot be negative ...

Thanks for help.

V

using System;
using System.Collections.Generic;
using System.Linq;
class Oef16
{
    public static void Main()
    {
        int match;
        Random rand = new Random();
        List<string> teams = new List<string>
            { "team A", "team B", "team C"};

        List<int> points = new List<int> { };

        for (int i = 0; i <= teams.Count - 1; i++)
        {
            for (int j = i + 1; j <= teams.Count - 1; j++)
            {
                match = rand.Next(1, 4); // 1 = team A wins, 2 = team B wins, 3 = even
                switch (match)
                {
                    case 1:
                        points[i] += 3;
                        break;
                    case 2:
                        points[j] += 3;
                        break;
                    default:
                        points[i] += 1;
                        points[j] += 1;
                        break;
                }
            }
            Console.ReadLine(); // stoppen na alle matchen van elke ploeg
        }
        int m = points.Max();
        int p = points.IndexOf(m);

        Console.WriteLine("Final ranking: the winner is " + teams[p] + " with " + points[p] + " points.");

        List<string> teampoint = new List<string> { };
        for (int i = 0; i <= teams.Count - 1; i++)
        {
            if (points[i] < 10)
                teampoint[i] = "0" + points[i] + " " + teams[i];
            else
                teampoint[i] = points[i] + " " + teams[i];
        }

        teampoint.Sort();
        teampoint.Reverse();

        foreach (string i in teampoint)
            Console.WriteLine(i);
    }
}


Answers (2)