2015-10-19 99 views
-2

只需要尋找一種方法來創建一些來自同一個類的一些(20)對象的循環 有沒有辦法做到這一點?在循環中創建對象

我嘗試使用Loopcount Int作爲一個沒有運氣的數字..任何想法?

static void Main(string[] args) 
{ 
    Student[] aStudent = new Student[20]; 

    for (int i = 0; i < 20; i++) 
    { 
     Console.WriteLine("Please enter the 2 grades for student num " + i+ " \nif there is no grade , enter -1"); 
     aStudent[i].FirstGrade = int.Parse(Console.ReadLine()); 
     aStudent[i].SecondGrade = int.Parse(Console.ReadLine()); 
    } 
} 
+3

你當然可以。首先你需要一種編程語言。然後你需要一堂課。那麼你需要一個你的嘗試的例子。然後我們會有想法。 – ergonaut

+0

抱歉:)我是一個noob在這裏我將編輯帖子 –

+0

我可以提出寶貴的建議嗎?除非你有足夠的理由這麼做,否則不要使用原始數組;你應該使用列表 students = new列表(); – Krythic

回答

0

您已經創建了一個數組,但尚未初始化數組中的項目。最簡單的改變就是在循環內創建一個新的實例:

for (int i = 0; i < 20; i++) 
{ 
    aStudent[i] = new Student(); 
    Console.WriteLine("Please enter the 2 grades for student num " + i+ " \nif there is no grade , enter -1"); 
    aStudent[i].FirstGrade = int.Parse(Console.ReadLine()); 
    aStudent[i].SecondGrade = int.Parse(Console.ReadLine()); 
} 
+0

非常感謝! –

+0

我會將aStudent添加到對象列表中,以便您可以在for循環之外使用 – KPS