Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Objects Loops and Final Touches Foreach Loops

Please check

Can somone please explain to me why my code doesnt work. Thank you

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            foreach(Frog frog in frogs)
            {
                int totalLengths = frog.TongueLength + totalLengths; 

                double tongueAverage = totalLengths / frogs.Length;

                return tongueAverage;

            }
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

        public Frog(int tongueLength)
        {
            TongueLength = tongueLength;
        }
    }
}

1 Answer

Jon Wood
Jon Wood
9,884 Points

I see a couple of things that may cause it not to compile:

  • You're using the totalLengths variable before it gets initialized. You can change this line: int totalLengths = frog.TongueLength + totalLengths; to something like this: int totalLengths = 0; totalLengths = frog.TongueLength + totalLengths;
  • You're returning inside of the foreach loop. You'll have to move it outside of the loop or else the compiler will yell about the method where not all paths have a return value.
  • For the algorithm itself, you're dividing while in the loop, as well. You just need the loop to get the sum of lengths and outside of it do the division.

You're doing great, though! Keep up the awesome job!