C# C# Objects Loops and Final Touches Foreach Loops

Pedro Gonzalez
Pedro Gonzalez
2,097 Points

I am stuck in the Foreach loop task. Any help is greatly appreciated

My code can't run because i get a compiling error stating "Cannot convert type Treehouse.CodeChallenges.Frog' todouble' ". So my question is How can I fix my code so I don't get this compiling error and what does it mean? Thank you in advance to whoever replies.

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

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

1 Answer

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

Hi there! Oh wow, you're really close here! Inside your foreach loop you're saying for every double i in the frogs array. But the frogs array doesn't contain a set of doubles. It contains a set of frogs of type Frog! :frog:

So your code is trying to explicitly cast a Frog to a double, which cannot be done and results in the compiler error. If I modify your code just slightly, it passes.

namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            double total = 0;
            foreach(Frog i in frogs)
            {
                total = total + i.TongueLength;                
            }
            return total/frogs.Length;
        }
    }
}

Now our i variable is of type Frog instead of a double. Hope this helps! :sparkles:

Pedro Gonzalez
Pedro Gonzalez
2,097 Points

Thank you so much for helping me.Hope you have a great day.