我試圖創建存儲固定裝置的清單列表方法。目前我一直在我的代碼的if (fixtures[i] != lineup)
部分出現錯誤,我不能解釋爲什麼。我不斷收到以下錯誤。C# - 生成固定裝置的列表,使用隨機
類型「System.ArgumentOutOfRangeException」的未處理的異常出現在mscorlib.dll
其他信息:索引超出範圍。必須是非負數且小於集合的大小。
我不明白爲什麼這是一個問題,因爲如果fixtures [i]肯定是null,那麼它應該添加陣容呢?
private List<string> GenerateFixtures()
{
List<string> fixtures = new List<string>(); // Create a new list to store the games
while (fixtures.Count < 7) // There can only be 6 possible games
{
Random random = new Random(DateTime.UtcNow.Millisecond); // Generate a new random
int home = random.Next(0, 3); // Home team number
int away = random.Next(0, 3); // Away team number
if (home == away) // If they are the same teams
{
while (home == away) // whilst they are equal to eachother
{
away = random.Next(0, 3); // generate new away team
}
}
string lineup = string.Format("{0} v {1}", home, away); // convert it to a string
for (int i = 0; i <= fixtures.Count; i++) // whilst i is 0
{
if (fixtures[i] != lineup) // if fixtures is not equal to lineup
fixtures.Add(lineup); // add it
}
} // loop through till it is done
return fixtures; // then return it
}
我也有點擔心,那我會對此產生錯誤的方式。我有4支球隊 - 球隊0,1,2和他們應該隨機對手(我使用隨機,以便其總是不同的陣容,因爲我打算用於其他組)。
0 V 1 || 2 v 3 || 2 v 1 || 3 v 0 || 1 v 3 || 0 V 2
有沒有更好的方式來做到這一點?
我也剛剛注意到,我這樣做的方式將允許0 v 1和1 v 0被添加到列表中,因爲它們是不同的。
你到底想幹什麼?創建一個沒有重疊對的列表?使用簡單的算法,比如鴿子而不是做隨機,你會更好。 – Codeman 2014-12-02 22:21:09
在循環外部移動創建Random。你可能會得到重複,只需要創建一次。 – 2014-12-02 22:22:27