I need help declaring an array of objects where the attributes of the properties are user inputted.
I have been tasked with creating an array of objects.
The Application for my assignment says that I need to create a job array in which the user is prompted for details to fill out the form. A job number, a name of the business, the hours it takes for the job to be completed.....
The first thing that I do is create a job class.
Easy peasy, than I deciare the job object
So I have to activate the class and create the objects.
jobOrder[0] = new jobOrder;
I say to myself what can I use to loop through this array and assign objects to each slot in the array. And when I do so I require the user to be prompted to input data.
So my question is, do I use a for loop and prompt the user for each attribute and than somehow assign it to an object?
Or do I use a constructor and make the object?
I am a little lost because this requires user input.
public CreateJob()
{
jobOrders[] jobOrder = new jobOrder[4];
for (int i = 0; i < jobOrders.Length; ++i)
Console.WriteLine($"Enter job number {i}");
Console.WriteLine($"Enter customer name {customerName}");
jobOrders[i].customerName = Console.ReadLine();
}
```
Solution Output
An example of the expected program is shown below:
Enter job number 1
Enter customer name Bobbi
Enter description Carpet Cleaning
Enter estimated hours 4
Enter job number 2
Enter customer name Sarah
Enter description Flooding
Enter estimated hours 12
Enter job number 3
Enter customer name Taylor
Enter description Flooring
Enter estimated hours 12
Enter job number 4
Enter customer name Sam
Enter description Gardening
Enter estimated hours 6
Enter job number 5
Enter customer name Alex
Enter description Renovations
Enter estimated hours 60
Summary:
RushJob 1 Bobbi Carpet Cleaning 4 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $330.00
RushJob 2 Sarah Flooding 12 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $690.00
RushJob 3 Taylor Flooring 12 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $690.00
RushJob 4 Sam Gardening 6 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $420.00
RushJob 5 Alex Renovations 60 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $2,850.00
Total for all jobs is $4,980.00
70 Replies
Got some errors in the code you posted, but I assume it's not the actual code. Just saying
Yes, a loop would definitely be a good idea here
Basically, for each slot, ask for a name, hours, price, then use those to create a new job instance and add it to the slot
Assuming that
jobOrders class is what you're using, you can use an object initializer to create it with the values you want, like:
you can also create the object first and set the values afterwards
And this is a nitpick, but classes are normally named WithACapitalLetterLikeThis, same with properties.Also known as
PascalCase, instead of camelCasethis seems to be what my textbook is telling me to attempt so I will try it soley based on the fact the text book is teaching this method. my question to you is, I would have to create a method that first creates the object, than like @ZZZZZZZZZZZZZZZZZZZZZZZZZ was saying make a for loop and colelct properties and than assign it.
Pascal case. Ok I will implement that now.
You don't need another method to create the object. C# lets you create objects like this if they have properties. You can do it directly in your for loop where you're gathering user input.
That said, making a separate method that handles the user input and creates and returns a job object could make the code a fair bit cleaner
public CreateJob()
{
jobOrders[] jobOrder = new jobOrder[4];
for (int i = 0; i < jobOrders.Length; ++i)
Console.WriteLine($"Enter job number");
// TryParse needed
intJobNumber = Console.ReadLine();
Console.WriteLine($"Enter customer name {customerName}"); jobOrders[i].customerName = Console.ReadLine(); } Like this? Would I capture the data in variables and than once that data is known in the scope of the method use those variables and the new operator to create the object and than return that object?
Console.WriteLine($"Enter customer name {customerName}"); jobOrders[i].customerName = Console.ReadLine(); } Like this? Would I capture the data in variables and than once that data is known in the scope of the method use those variables and the new operator to create the object and than return that object?
Something like that would work, yes
TIME TO CODE! 🙂
I'll let you know how it goes once I am done I'll post my solution for feedback.
:Ok:
@ded @ZZZZZZZZZZZZZZZZZZZZZZZZZ
something like this?
public CreateJob()
{
jobOrders[] jobOrder = new jobOrder[5];
double jobPrice = 45.00;
for (int i = 0; i < jobOrders.Length; ++i)
Console.WriteLine($"Enter job number ");
string jobNum = Console.ReadLine();
// int jobNumber is created on the tryparse
int.TryParse(jobNum, out int jobNum);
Console.WriteLine($"Enter customer name "); string cust = Console.ReadLine(); Console.WriteLine($"Enter description "); string desc = Console.ReadLine(); Console.WriteLine($"Enter estimated hours "); int.TryParse(Console.ReadLine(), out int jobHours); jobOrders[i] = new Job { jobNumber = jobNumber, customerName = cust, description = desc, jobHours = jobHours, jobPrice = price };
}
Console.WriteLine($"Enter customer name "); string cust = Console.ReadLine(); Console.WriteLine($"Enter description "); string desc = Console.ReadLine(); Console.WriteLine($"Enter estimated hours "); int.TryParse(Console.ReadLine(), out int jobHours); jobOrders[i] = new Job { jobNumber = jobNumber, customerName = cust, description = desc, jobHours = jobHours, jobPrice = price };
}
try it and see
It declared dmy project invalid and would not build. attempting troubleshooting.
resolving errors.... still on it.
Take your time, there's no rush
Or, if an error is particularly hard to solve, feel free to ask
What I am thinking so far.....
I was taught to keep functions simple. So after much struggling I have the job function just return an object with Console.Write prompts and Console.Readline(). if the tryparse works out, than the value is stored.
However, I need tdo fill an array with objects. so I need to initalize an object array. Probably in Main.
Im going to take a walk. I am frustrated.d
Aside of some odd choices (
Job class being nested in JobDemo3 class, CreateJob() not being static) this looks perfectly fine
Now you just need to run the CreateJob() method in a loop
It creates one job, you need multipleOn it.
static void Main()
{
// Write your code here
Job[] job = new Job[5];
var job = new Job().CreateJob(); // instance method version
}
}
Almost. You have the same variable name for your array and your single job, and that
CreateJob method really should be static at this point so you dont need to create an instance of Job first.@Pobiega
Here is where I am at now. I am under the impression that get set methods are utlized to access private members data without actually changing the private data. This protects the class from um, inexperienced programmers such as myself. Even so public get set methods are supposed to retrieve data. So why is it complaining about this? Error: CS1520: Method must have a return type. I have reimplemented the Job data type for now to satisfy return conditions. New error: C:\Users\Andrew\QuickAccess Groups\Programming_projects\DallasCollege\INEW-1340-1-ASP.NET Programming\ASPApp\JobDemo3App\JobDemo\JobDemo.cs(38,24): error CS0102: The type 'JobDemo3.Job' already contains a define Per copilots explanation The error means you declared the same member name twice in the same type. In your file you have both private fields and auto-properties with identical names (for example both private int jobNumber = 0; public int jobNumber { get; set; } C:\Users\Andrew\QuickAccess Groups\Programming_projects\DallasCollege\INEW-1340-1-ASP.NET Programming\ASP.NET_DallasCollege-main\CSharp-Intermediate-Dallas-College\Chapter10\10_3\JobDemo3App\JobDemo3App\JobDemo\JobDemo.cs(38,24): error CS0102: The type 'JobDemo3.Job' already contains a definition for 'jobNumber' My program is complaining about not being able to use the index for the for loop for the JobSummary method.
Here is where I am at now. I am under the impression that get set methods are utlized to access private members data without actually changing the private data. This protects the class from um, inexperienced programmers such as myself. Even so public get set methods are supposed to retrieve data. So why is it complaining about this? Error: CS1520: Method must have a return type. I have reimplemented the Job data type for now to satisfy return conditions. New error: C:\Users\Andrew\QuickAccess Groups\Programming_projects\DallasCollege\INEW-1340-1-ASP.NET Programming\ASPApp\JobDemo3App\JobDemo\JobDemo.cs(38,24): error CS0102: The type 'JobDemo3.Job' already contains a define Per copilots explanation The error means you declared the same member name twice in the same type. In your file you have both private fields and auto-properties with identical names (for example both private int jobNumber = 0; public int jobNumber { get; set; } C:\Users\Andrew\QuickAccess Groups\Programming_projects\DallasCollege\INEW-1340-1-ASP.NET Programming\ASP.NET_DallasCollege-main\CSharp-Intermediate-Dallas-College\Chapter10\10_3\JobDemo3App\JobDemo3App\JobDemo\JobDemo.cs(38,24): error CS0102: The type 'JobDemo3.Job' already contains a definition for 'jobNumber' My program is complaining about not being able to use the index for the for loop for the JobSummary method.
Ok let's start with clearing up what a property is and does.
a property is a class member that has the
{ get; set; } bit (note that you might see variations to this, like only a getter, private setter etc)
now, these properties are backed by a private field - but that is hidden from you and not something to consider most of the time
In fact, thats where { get; private set; } becomes very useful!
that means you have a private setter, so your class can modify the value as much as it wants, while "everyone else" can only access the value via the getter
so you dont need to declare your own backing field
Thus, your code...
doesnt actually connect these two values at all
@strikeouts27reading now....
yeah sorry was working, but I have a while now so feel free to ask and I'll "live" reply 🙂
using System;
using static System.Console;
using System.Globalization;
namespace JobDemo3
{
class JobDemo3
{
static void Main()
{
// Write your code here
Job[] jobs = new Job[5];
for (int i = 0; i < jobs.Length; i++)
{
var newJob = new Job().CreateJob();
jobs[i] = newJob;
}
} // Job Class public class Job { private int jobNumber = 0; private string customerName; private string description; private int jobHours; private double price; public int CreateJobNumber(int jobNumber) { this.jobNumber++; return jobNumber; } public int JobNumber { get; set; } public string CustomerName { get; set; } public string Description { get; set; } public int JobHours { get; set; } public double Price { get; set; } // I want to create an array that is empty and can hold different data types. // I than want to create a series of prompts for the user to input the values into variables. // I than want the array to have those values be assigned in the designated slots. public Job CreateJob() { var job = new Job(); Console.Write("Enter job number: "); if (int.TryParse(Console.ReadLine(), out int num)) job.jobNumber = num; Console.Write("Enter customer name: "); job.customerName = Console.ReadLine() ?? string.Empty; Console.Write("Enter description: "); job.description = Console.ReadLine() ?? string.Empty; Console.Write("Enter estimated hours: "); if (int.TryParse(Console.ReadLine(), out int hours)) job.jobHours = hours; Console.Write("Enter price: "); if (double.TryParse(Console.ReadLine(), NumberStyles.Any, CultureInfo.CurrentCulture, out double p)) job.price = p; return job; } public double CalculateJobPrice(double JobHours, double Price) { double JobTotalCost = JobHours * Price; return JobTotalCost; } public string JobSummary(int JobHours, double Price, int index) { Console.WriteLine("Summary:"); Console.WriteLine("\n"); Console.WriteLine($"RushJob {JobSummary[index].JobSummary(i)} Bobbi Carpet Cleaning {JobHours} hours @{Price} per hour. Rush job adds {JobTotal}"); } }
// RushJob Class s public class RushJob : Job { private double premiumFee = 150.00; // preimum calculation } // CertifiedLetter Class // Child class of Job that adds a tracking number property public class CertifiedLetter : Job { // Auto-implemented nullable property to hold the tracking number public string? TrackingNumber { get; set; } } } } here is the code as it stands currently one sec
} // Job Class public class Job { private int jobNumber = 0; private string customerName; private string description; private int jobHours; private double price; public int CreateJobNumber(int jobNumber) { this.jobNumber++; return jobNumber; } public int JobNumber { get; set; } public string CustomerName { get; set; } public string Description { get; set; } public int JobHours { get; set; } public double Price { get; set; } // I want to create an array that is empty and can hold different data types. // I than want to create a series of prompts for the user to input the values into variables. // I than want the array to have those values be assigned in the designated slots. public Job CreateJob() { var job = new Job(); Console.Write("Enter job number: "); if (int.TryParse(Console.ReadLine(), out int num)) job.jobNumber = num; Console.Write("Enter customer name: "); job.customerName = Console.ReadLine() ?? string.Empty; Console.Write("Enter description: "); job.description = Console.ReadLine() ?? string.Empty; Console.Write("Enter estimated hours: "); if (int.TryParse(Console.ReadLine(), out int hours)) job.jobHours = hours; Console.Write("Enter price: "); if (double.TryParse(Console.ReadLine(), NumberStyles.Any, CultureInfo.CurrentCulture, out double p)) job.price = p; return job; } public double CalculateJobPrice(double JobHours, double Price) { double JobTotalCost = JobHours * Price; return JobTotalCost; } public string JobSummary(int JobHours, double Price, int index) { Console.WriteLine("Summary:"); Console.WriteLine("\n"); Console.WriteLine($"RushJob {JobSummary[index].JobSummary(i)} Bobbi Carpet Cleaning {JobHours} hours @{Price} per hour. Rush job adds {JobTotal}"); } }
// RushJob Class s public class RushJob : Job { private double premiumFee = 150.00; // preimum calculation } // CertifiedLetter Class // Child class of Job that adds a tracking number property public class CertifiedLetter : Job { // Auto-implemented nullable property to hold the tracking number public string? TrackingNumber { get; set; } } } } here is the code as it stands currently one sec
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif in chat
For longer snippets, use: https://paste.mod.gg/please use this so its easier to read
That is a game changer! 🙂
okay, so now you have compilation errors about duplicate members yes?
these conflict
so your saying they cannot be named the same.
Well thats true, but thats not my main point
You don't need both
Pick one. Most likely the property
and maybe change it to be
public int JobNumber { get; private set; }Um so get; set; gets the values and retrieves them, without properties how will my code get past the private lock?
it wont
so thats why you probably want to use the property
If I do not set a field value, than the class is incapable of holding that value correct?
no
properties have backing fields
they are automatic
backing fields are the targets of the get set right? they grab the fields of the class? Or am I mistaken.
it makes its own hidden field
oh cool
okay reattempting
um
-___- one sec
sounds like you moved your csproj file? 😄
I found a blurb I wanted to show you: $propvsfield
Why use properties over a public field?
- Properties can individually specify access modifiers for get and set
- With Visual Studio, you can type prop, press tab and it will auto complete for you
- XAML requires properties for bindings
- Many APIs don't handle public fields by default, such as json serialization
- Field exposure is really only done in readonly structs
- Using properties allows for future changes to the getter or setter without breaking your API/external programs (binary compatibility)
Example of an auto property:
Example of a property with backing field:
here you have an example of an auto property and a manually implemented backing field
they are functionally the same, but obviously the auto one is much cleaner
so we mostly only use that
so the get set can act as a field and as its own value. its a field with a protection on it
kinda
a property is actually 2 methods and a field, all in one
the getter, the setter, and the backing field
Reviewing
if the get set has a backing field that stores the value, than what is the purpose of getting and setting it?Is that for other methods to grab that value without influencing the backing field?
encapsulation and/or modifiability
you can change what a getter or setter does
and doing so wouldnt require a change in other classes that use your property
ok one more thing
you're still refering to the lowerCased
jobNumber somewhere
one sec i will find it and change it
theres a few of em
also, Im very confused about
CreateJobNumberThe programs requirements force me to verify that there are no repeat job numbers.
its public, it takes a number in, it mutates the member field, it then returns the same number you passed in?
Pobiega
REPL Result: Success
Console Output
Compile: 529.408ms | Execution: 50.198ms | React with ❌ to remove this embed.
example of a computational getter
is that the expected output?
Correct
As you can see, the job number, is quite straight forward!
So if it increments by one. it can never be the same. Unless some doofus messes with it.
hm okay
Any particular reason you are entering the job number, instead of just letting the computer keep track of a counter?
Hmmmmm I am inexperienced and trying to understand you. One moment.
Ah now I get what you are saying.
Well the requirements show an output where one must enter the job number.
fair enough
deffo gets problematic having to verify that as you go thou, but its doable.
it means the job creator needs to have access to all previously created jobs
This one I think i understand. and this is what I have been stuck on.
doggonit that is hard to read. one sec
Well, what are you trying to index there?
JobSummary is a method
you can't index methodsCorrect, wishful thinking.
I am so close to the goal line, but this error frustrates me.
I need it to show an index number.
I have considered dusing a for loop to increment by one just as the job is incremented. So when the object is created and the job number is incremented by one, it is stuck in that zone.
But i can mimic the job number in job summary if I know that it is incremented by one.
By that I mean, if job object one is created,
I could in a separate method call a for loop and increment by one?
start from the data
where is your job data right now? that will be your source
my job data is imaginary. It is not based on real world data. I can create the objects and provide the data. it just needs to mimic the job output
Enter job number 1
Enter customer name Bobbi
Enter description Carpet Cleaning
Enter estimated hours 4
Enter job number 2
Enter customer name Sarah
Enter description Flooding
Enter estimated hours 12
Enter job number 3
Enter customer name Taylor
Enter description Flooring
Enter estimated hours 12
Enter job number 4
Enter customer name Sam
Enter description Gardening
Enter estimated hours 6
Enter job number 5
Enter customer name Alex
Enter description Renovations
Enter estimated hours 60
Summary:
RushJob 1 Bobbi Carpet Cleaning 4 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $330.00
RushJob 2 Sarah Flooding 12 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $690.00
RushJob 3 Taylor Flooring 12 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $690.00
RushJob 4 Sam Gardening 6 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $420.00
RushJob 5 Alex Renovations 60 hours @$45.00 per hour. Rush job adds 150 premium. Total price is $2,850.00
Total for all jobs is $4,980.00
No I mean in the code
you cant print the jobs until after you have created them, and when creating them, you store them somewhere
start there
so utlize object instantiation, create the 5 jobs, store them in the array, than maybe uh.... call the job summary() method?
something like that yeah
This would initalize the objects
You have given me a great deal of insight, and I am grateful to you. I will keep fighting this problem.
I didn't mean to keep you on this but I really needed help. Thank you @Pobiega
so after that loop, you'll have your
jobs array
thats where your data is now
so make JobSummary take in that array as part of its inputs
something like this?