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 trialPedro Gonzalez
2,097 PointsI 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' to
double' ". 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.
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;
}
}
}
namespace Treehouse.CodeChallenges
{
public class Frog
{
public int TongueLength { get; }
public Frog(int tongueLength)
{
TongueLength = tongueLength;
}
}
}
1 Answer
Jennifer Nordell
Treehouse TeacherHi 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!
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!
Pedro Gonzalez
2,097 PointsPedro Gonzalez
2,097 PointsThank you so much for helping me.Hope you have a great day.