Reputation: 49
I'm new to C# programming. I was trying to create new objects (in my case StudentInfo
object) and place them in the array studentArr
.
The array is initialized with a length = 5 and I want to create five StudentInfo
objects and add them to the array. I don't think it's doing that at all and I don't know where I'm going wrong.
I'm supposed to enter student information through Console.Readline
for five different students and it's only printing out the first student information.
I'm using struct to access the student info.
Some help will be greatly appreciated!
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;
}
}
Upvotes: 2
Views: 68
Reputation: 5771
You are printing only the first element at 0 by writing studentArr[0]. It should be 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);
}
Upvotes: 3