0

I'm new to c# and having a hard time figuring out how to populate an array from user input. I have an array of 5 job objects

static Job[] jobArray = new Job[5];

The user will be inputting a description for each job, time to complete each job and the pay for each job. I need to put those inputted values into the array. Any help would be appreciated, thanks.

1
  • Your question probably is being downvoted because it is such a beginner question. Sometimes this causes instinctual hatred in people. Like "How can he not know that?!". Fyi. Your question seems fine to me. The problem is clearly defined. Otherwise, welcome to the site. Commented Oct 2, 2016 at 19:29

2 Answers 2

2

Basically what you need to keep in mind is that the row above where you initialize an array does not create the objects within it but only the array.

For each position of the array you need to request the information from the user and store it in the proper property. Then you assign that new object to the array.

This code sample does it for the Description, Hours and Pay properties of Job

Job[] jobArray = new Job[5];

for (int i = 0; i < jobArray.Length; i++)
{
   Job job = new Job();

   Console.WriteLine("Job " + i);

   Console.WriteLine("Enter description:");
   job.Desciption = Console.ReadLine();

   Console.WriteLine("Enter hours:");
   job.Hours = Console.ReadLine();

   Console.WriteLine("Enter pay:");
   job.Pay = Console.ReadLine();

   jobArray[i] = job;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, for the other fields (hours, pay) would i use 2 other arrays?
@John - see update. You do not need other arrays but just to set the properties of the items you are already creating
0

Make a function to read a Job:

static Job ReadJob() {
 return new Job() {
  Name = Console.ReadLine(),
  Description = Console.ReadLine(),
  //...
 };
}

And then fill the array:

for (int i = 0; i < jobs.Length; i++)
 jobs[i] = ReadJob();

Endless variants of this are possible.

1 Comment

This is the right solution, with good level of encapsulation. It's odd that anyone would downvote this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.