Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Loops and Final Touches For Loops

Yuyang Peng
Yuyang Peng
5,665 Points

Help with constructor class? ( I don't actually know what it is.... -_-)

Would appreciate if someone can explain why we can use a class/constructor as an array..does it mean it only contains what the getter gives us, which in this case the TongueLength? But when we declare Frog in other classes it needs to take a parameter.. so we are actually setting it...? but it doesn't have a setter..? i am truly a mess errgh. Thank you in advance :P

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            int tongueLength;
            for(int i = 0; i < frogs.Length; i++)
            {
                tongueLength += frogs[i].TongueLength;
            }
            return (double) tongueLength / frogs.Length ;
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

        public Frog(int tongueLength)
        {
            TongueLength = tongueLength;
        }
    }
}
Matti Mänty
Matti Mänty
5,885 Points

In GetAverageTongueLength, you are not actually using the constructor or the class as an array. GetAverageTongueLength is a method that expects you to input an array of Frog objects.

First, you need to create those frog objects, like this:

Frog frogOne = new Frog(5);
Frog frogTwo = new Frog(3);
// and so on

And yes, you need to set the tongue length when creating the Frog object. Frog constructor takes the length as a parameter and sets it in the code to TongueLength. Then you would create a new array of the class Frog, put those Frog objects into that array. You can then finally use this array to call the FrogStats' method.

Frog[] frogArray = new Frog[] {frogOne, frogTwo};
double average = FrogStats.GetAverageTongueLength(frogArray);

1 Answer

Yuyang Peng
Yuyang Peng
5,665 Points

Thank you man! That's well explained !