Search code examples
c#fizzbuzz

FizzBuzz test case pass


I am wondering can someone please tell me where I am going wrong with this FizzBuzz.

I get an error "not all code returns a value and struggling to find out exactly how to fix it.

My code is below:

for (int i = 0; i < input; i++)
{
    if (i % 3 == 0)
    {
        Console.WriteLine("Fizz");
    }
    else if (i % 5 == 0)
    {
        Console.WriteLine("Buzz");
    }
    else if (i % 3 == 0 && i % 5 == 0)
    {
        Console.WriteLine("FizzBuzz");
    }
    else
    {
        Console.WriteLine(i);
    }
}

And the test case is this:

[Test]
public void Test1()
{
    var solution = new Solution();

    Assert.AreEqual(solution.PrintFizzBuzz(15), "FizzBuzz");    
}

Solution

  • First of like other people have said, not all the code is present so it's difficult for us to help. But I'll try anyway.

    When testing with Assert.AreEqual the function PrintFizzBuzz should return something, in this case the string "FizzBuzz". But if you are using the Console.WriteLine method it will return nothing. The Console.Writeline method will print the string to the console, but the console is not actually the 'program', it's just for visualising some things like logging or debugging.

    So to fix your issue you should use return instead of Console.Writeline and let your method PrintFizzBuzz return a string instead of voiding and printing it to the console. It's probably also better to rename your method in this case, because it doesn't print FizzBuzz anymore.

    Your code has also another issue and that's when you input 15 it will print out "Fizz", because the check you do is modulo 3 and 15 % 3 = 0. You should order your check the otherway around, from specific to less specific.

    An example for returning a string would be:

    string SomeMethod()
    {
        return "Some String"
    }