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 trialAndrew Perry
5,266 Pointswhy does this code not compile?
I know what the solution is to this exercise, I need to delete the else statement and then have the method return false outside of the for loop. I don't understand why I can't return false with an else statement inside the for loop though.
namespace Treehouse.CodeChallenges
{
class SequenceDetector
{
public virtual bool Scan(int[] sequence)
{
return true;
}
}
class RepeatDetector : SequenceDetector
{
public override bool Scan(int[] sequence)
{
for(int i = 1; i < sequence.Length; i++)
{
if(sequence[i] == sequence[i-1])
{
return true;
}
else
{
return false;
}
}
}
}
}
1 Answer
christopher vaughan
1,411 Pointsit doesn't compile because there's a possibility that the for loop will never run, in which case override lacks a return statement. for instance if sequence.Length == 0, i is never less than sequence.Length, so the for loop wouldn't trigger at all.
int[] sequence; //sequence has no length
for(int i = 1; i < sequence.Length; i++){ //this will never execute
}
Andrew Perry
5,266 PointsAndrew Perry
5,266 Pointsmakes sense, thanks for your help.