0

I dont understand methods fully yet, and i dont know why is this happening... Im trying to make my code change ints to words, and i think this is the way to go.

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            Console.WriteLine("Hi wanna play rock paper scissors?<press enter to continue>");
            Console.ReadKey();
            int user = 0;
            int ai = r.Next(1, 4);
            Console.WriteLine("Pick what youll show! (1-rock, 2-paper, 3-scissors) and press enter");
            user = Convert.ToInt32(Console.ReadLine());
            if (user > 3)
            {
                Console.WriteLine("ERROR! your number must be <= 3. <Press enter to close the program>");
                goto end;
            }
            if (user == ai)
            {
                Console.WriteLine("Its a draw! <press enter to continue>");
                goto end;
            }


            Console.WriteLine(user);

end:
Console.ReadKey();
        }
        public static string ntw (int user) //ntw: not all code paths return a value
    {
        if (user == 1)
            return "rock";
        if (user == 2)
            return "paper";
        if (user == 3)
            return "scissors";

    }
    }
}

Thanks in advance.

tagito
  • 31
  • 1
  • 6

3 Answers3

9

Your method's return type is string. That means your method should always return some string value. With your current implementation it is returning some string when the value of user variable is 1 or 2 or 3. What if you call this method with value 25 ? The compiler does not know what to do!

Your method should return some string if the user value is not 1 or 2 or 3

public static string ntw (int user)
{
     if (user == 1)
        return "rock";
     if (user == 2)
         return "paper";
     if (user == 3)
         return "scissors";

     return string.empty; // Here i am returning an empty string.
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
1

You could also use a switch statement, in this case the default would give u a Null or an empty string if the user isn't 1, 2 or 3 :)

    public static string ntw (int user)
    {
        switch (user)
        {
            case 1:
                return "rock";
            case 2:
                return "paper";
            case 3:
                return "scissors";
            default:
                return null; // or return string.Empty
        }
    }
Dave Wijnen
  • 71
  • 2
  • 7
0

If the values must be in range 1..3 (and returning the string.Empty string has no sense) then you can write:

public static string ntw (int user) 
{
    if (user == 1)
        return "rock";
    if (user == 2)
        return "paper";
    if (user == 3)
        return "scissors";
    throw new ArgumentException("Invalid choice");
}

and handle the exception somewhere in the program.

romanoza
  • 4,775
  • 3
  • 27
  • 44