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 trialRyan Silva
1,071 PointsHow can I get the sum of the frog's tongue length?
In my for loop, I've been trying "int total = frogs[i]++;" to try and add the values of each frog's tongue length in each element of the array but it's been giving me an error and I'm not sure how to get it to work properly.
namespace Treehouse.CodeChallenges
{
class FrogStats
{
public static double GetAverageTongueLength(Frog[] frogs)
{
for (int i = 0; i < frogs.Length; i++)
{
int total = frogs.tongueLength[i]++;
}
double average = total / frogs.Length;
return average;
}
}
}
namespace Treehouse.CodeChallenges
{
public class Frog
{
public int TongueLength { get; }
public Frog(int tongueLength)
{
TongueLength = tongueLength;
}
}
}
1 Answer
Steven Parker
231,275 PointsDoing frogs[i]++
would try to increment the frogs themselves, which doesn't make sense.
And frogs.tongueLength[i]++
would try to increment the tongue length of each of several tongues.
But to add them together, you need to iterate through the frogs and access their lengths. So you'd want to use frogs[i].tongueLength
which is the tongue length of each frog. Then to add them all to the total you might write total += frogs[i].tongueLength
. Note that you can't use the addition assignment and declare the variable at the same time, so you'll want to initialize total to 0 before the loop starts.
Ryan Silva
1,071 PointsRyan Silva
1,071 PointsAwesome, that helped and I got it working. Thank you!!