我是C#編程新手。我試圖創建新的對象(在我的案例StudentInfo
對象),並將它們放入數組studentArr
。爲什麼控制檯不斷爲我的數組中的元素寫入相同的輸出?
數組初始化的長度爲5,我想創建五個StudentInfo
對象並將它們添加到數組中。我不認爲它是這樣做的,我不知道我哪裏會出問題。
我應該通過Console.Readline
爲五個不同的學生輸入學生信息,它只打印出第一個學生信息。
我使用struct來訪問學生信息。
一些幫助將不勝感激!
static void Main(string[] args)
{
StudentInfo[] studentArr = new StudentInfo[5];
int objectNumber = 0;
for (int i = 0; i < studentArr.Length; i++)
{
studentArr[i] = new StudentInfo();
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
studentArr[i].firstName = Console.ReadLine();
studentArr[i].lastName = Console.ReadLine();
studentArr[i].birthDay = Console.ReadLine();
studentArr[i].studentID = Console.ReadLine();
studentArr[i].addressLine1 = Console.ReadLine();
studentArr[i].addressLine2 = Console.ReadLine();
studentArr[i].city = Console.ReadLine();
studentArr[i].state = Console.ReadLine();
studentArr[i].zipCode = Console.ReadLine();
studentArr[i].country = Console.ReadLine();
objectNumber = i + 1;
}
for (int i = 0; i < studentArr.Length; i++)
{
Console.WriteLine(
"{0} {1} was born on {2}. Student ID: {3}",
studentArr[0].firstName, studentArr[0].lastName,
studentArr[0].birthDay, studentArr[0].studentID);
Console.WriteLine(
"Address: {0} {1} \n\t {2} {3} {4} {5}.",
studentArr[0].addressLine1, studentArr[0].addressLine2,
studentArr[0].city, studentArr[0].state, studentArr[0].zipCode,
studentArr[0].country);
}
}
public struct StudentInfo
{
public string firstName;
public string lastName;
public string birthDay;
public string studentID;
public string addressLine1;
public string addressLine2;
public string city;
public string state;
public string zipCode;
public string country;
// Constructor for StudentInfo
public StudentInfo(
string first, string last, string dob, string ID,
string address1, string address2, string city,
string state, string zip, string country)
{
this.firstName = first;
this.lastName = last;
this.birthDay = dob;
this.studentID = ID;
this.addressLine1 = address1;
this.addressLine2 = address2;
this.city = city;
this.state = state;
this.zipCode = zip;
this.country = country;
}
}
你總是在訪問第一個數組元素在你的'for'循環,改變'studentArr [0]''到studentArr [I]' – chomba
什麼'objectNumber'做? – ahjohnston25
小提示:由於您按照建議一遍又一遍地聲明'studentArr [0]',因此聲明一個局部變量,如'var currentStudent = studentArray [0]'。或者只是使用'foreach'循環,因爲您沒有將索引用於枚舉之外的任何內容。 – ryanyuyu