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 trialMitchell Sharber
16,710 PointsCannot pass quiz, Says to double check logic for Fizz values...
Can anyone explain why this is incorrect? I believe I have made the correct changes outlined in the steps for the challenge, and my code passes in Xcode...
func fizzBuzz(n: Int) -> String {
// Enter your code between the two comment markers
for n in 1...100 {
if (n % 3 == 0) && (n % 5 == 0) {
return "FizzBuzz"
} else if (n % 3 == 0) {
return "Fizz"
} else if (n % 5 == 0) {
return "Buzz"
} else {
return "\(n)"
}
}
// End code
return "\(n)"
}
3 Answers
Steve Hunter
57,712 PointsHI Mitchell,
Looking at the way that is structured, the challenge is not expecting a for
loop.
The code is placed inside a method. That method takes an integer as a parameter and returns a string.
The user of the method is expecting to pass in a number, n
, and receive back one of four things; all strings. The returned value can be "Fizz", "Buzz", "FizzBuzz" or a default value that is handled for you. The method tests one number at once - it does not loop through 100 each time it is called.
You can nest a load of if and else if statements to test each n
passed in, as you have done.
Make sense?
Steve.
Richard Lu
20,185 PointsHey Mitchell,
The Challenge is to paste in some generic FizzBuzz logic. So you don't need the for loop:
if (n % 3 == 0) && (n % 5 == 0) {
return "FizzBuzz"
} else if (n % 3 == 0) {
return "Fizz"
} else if (n % 5 == 0) {
return "Buzz"
} else {
return "\(n)"
}
The challenge also mentions
Do not worry about the default case (where the number doesn't match Fizz, Buzz, or FizzBuzz). The code in the challenge editor already takes care of that by returning the number as a string using string interpolation.
Therefore you can shorten your solution to just
if (n % 3 == 0) && (n % 5 == 0) {
return "FizzBuzz"
} else if (n % 3 == 0) {
return "Fizz"
} else if (n % 5 == 0) {
return "Buzz"
}
Your final result should look something like this
func fizzBuzz(n: Int) -> String {
// Enter your code between the two comment markers
if (n % 3 == 0) && (n % 5 == 0) {
return "FizzBuzz"
} else if (n % 3 == 0) {
return "Fizz"
} else if (n % 5 == 0) {
return "Buzz"
}
return "\(n)"
}
Happy coding. Good luck! :)
Mitchell Sharber
16,710 PointsGot it to work! Thanks to both of you for your help!
Steve Hunter
57,712 PointsGood work - glad you got it fixed!
Richard Lu
20,185 PointsWoop woop! Hurray! :)