C# C# Basics If Statements "else if" and "else" Statements

Patrick Palmowski
Patrick Palmowski
4,041 Points

C# beginner´s Course / final challenge return statement

So what do I have to Change in line 20?

I just cant find an answer on the web

Program.cs
using System;

class Program
{

    static string CheckSpeed(double speed)
    {
        if(speed > 65)
        {
            Console.WriteLine("too fast");
        }
        else if(speed < 45)
        {
            Console.WriteLine("too slow");
        }
        else
        {
            Console.WriteLine("speed OK");
        }
        return speed;
    }

    static void Main(string[] args)
    {
        // This should print "too slow".
        Console.WriteLine(CheckSpeed(44));
        // This should print "too fast".
        Console.WriteLine(CheckSpeed(88));
        // This should print "speed OK".
        Console.WriteLine(CheckSpeed(55));
    }

}

5 Answers

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,914 Points

If you just delete line 20 you have no return statements which is why you receive the error. You also need to replace Console.WriteLine with return . Then your code paths will be returning .a value

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,914 Points

The challenge asks you to return strings not write to the console. Line 20 should be deleted altogether.

Patrick Palmowski
Patrick Palmowski
4,041 Points

If it wouldn´t be a challenge, I could also change from "static string" to "static double", right?

Patrick Palmowski
Patrick Palmowski
4,041 Points

Hey thanks KRIS, but when I delete it, I get this message:

Program.cs(6,19): error CS0161: 'Program.CheckSpeed(double)': not all code paths return a value [/workdir/workspace.csproj]

The build failed. Please fix the build errors and run again.

Im a bit confused Right so not just my Code on line 20 is wrong.. but also the rest?

Patrick Palmowski
Patrick Palmowski
4,041 Points

using System;

class Program {

static string CheckSpeed(double speed)
{
    string answer;
    if(speed > 65)
    {
        answer = "too fast";
    }
    else if(speed < 45)
    {
        answer = "too slow";
    }
    else
    {
        answer = "speed OK";
    }
    return answer;

}

static void Main(string[] args)
{
    // This should print "too slow".
    Console.WriteLine(CheckSpeed(44));
    // This should print "too fast".
    Console.WriteLine(CheckSpeed(88));
    // This should print "speed OK".
    Console.WriteLine(CheckSpeed(55));
}

}

Sometimes reading is just the answer thank You @KRIS NIKOLAISEN