Trying to add GrossWeight each time it shows up in the list
Trying to learn how to use a ForEach loop while doing my homework. I feel like this should be easier than it is, but basically I am trying to add the grossweight by each other every time one is found in my list. Once I do that I need to add the weight of the engine and return the whole equation sum out of the method. If more code is needed please go ahead and ask, I'll provide.
24 Replies
you need another variable for total weight
Create a new variable outside of the loop and keep adding to that
grossweight changes for every object in list/array
I have one already called MaxGrossWeight should I pass that into the method?
Why?
You want to return a sum from this method
Can't I use that for total weight?
Idk
Should it store total weight?
You can but it's unnecessary
Oh nah it doesn't just seen
It's horsepower * 2000
so I need to make a new variable right above the loop
Ok so I've done that
You can paste code into this chat and make it look fancy right?
$codegif
Yep
Didn't turn out that good but we learning
Well, you're not using this variable yet
Yeah
You'll need some starting value for it.
0
would seem reasonable
Then, in the loop, keep adding to that variableOk so I need my total weight to basically take in my grossweight each time
Instead of to
GrossWeight
Would it be totalGrossWeight += GrossWeight?
also you need to return totalGrossWeight
yeah
Ahh ok
And now for the last part my engine is a class that has a Weight given in the constructor
I thought passing in Engine.Weight would fit in my method but it says it cannot find it in context, my guess is that it's set to readonly?
It's a field of
Engine
When you're trying to set the weight of an engine, which engine's weight do you want to set?
You need an instance, a specific engine that can have weight
A class is just a blueprint, so to speak. The actual object is the instance of a class
Besides that, yes, those fields are readonly, so they can only be set from the ctorAhh ok
My engine only has one Weight
Compared to my train which has multiple
I have this passed into my train program
I just don't know what would be necessary to grab the weight from the engine class
Sorry if I sound like a noob I started c# 6 months ago
I think I'm close to figuring out the rest from here, thanks for the help guys It made much more sense when I realized I had to initialize the variable first.