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,883 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!