我是 C# 编程新手。我试图创建新对象(在我的例子中是 StudentInfo
对象)并将它们放入数组 studentArr
中。
数组初始化为 length = 5,我想创建五个 StudentInfo
对象并将它们添加到数组中。我认为它根本没有这样做,我也不知道我哪里错了。
我应该通过 Console.Readline
输入五个不同学生的学生信息,但它只打印出第一个学生信息。
我正在使用结构来访问学生信息。
我们将不胜感激一些帮助!
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;
}
}
最佳答案
通过编写studentArr[0],您仅打印位于0 处的第一个元素。应该是studentArr[i]
for (int i = 0; i < studentArr.Length; i++)
{
Console.WriteLine("{0} {1} was born on {2}. Student ID: {3}", studentArr[i].firstName, studentArr[i].lastName, studentArr[i].birthDay, studentArr[i].studentID);
Console.WriteLine("Address: {0} {1} \n\t {2} {3} {4} {5}.", studentArr[i].addressLine1, studentArr[i].addressLine2, studentArr[i].city, studentArr[i].state, studentArr[i].zipCode, studentArr[i].country);
}
关于c# - 为什么控制台不断为数组中的元素写入相同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29906279/