Search code examples
c#consoleconsole-applicationwindows-console

Class / Method not returning the correct value


Probably a pretty newb question but here we go.

I am quite new to this and right now i have reached my first logic problem i guess.

I've created a class + method which is supposed to return me a Int32 value and it returns something that is, atleast in my eyes, unreachable. I also dont want this value to be returned.

Here's the code:

    public static Int32 SetInterval(ConsoleKeyInfo cki)
    {
        if (cki.Key == ConsoleKey.D1 || cki.Key == ConsoleKey.D2 || cki.Key == ConsoleKey.D3 || cki.Key == ConsoleKey.D4 || cki.Key == ConsoleKey.D5 || cki.Key == ConsoleKey.D6)
        {
            if (cki.Key == ConsoleKey.D1)
            {
                return 10000;
            }
            else if (cki.Key == ConsoleKey.D2)
            {
                return 20000;
            }
            else if (cki.Key == ConsoleKey.D3)
            {
                return 30000;
            }
            else if (cki.Key == ConsoleKey.D4)
            {
                return 45000;
            }
            else if (cki.Key == ConsoleKey.D5)
            {
                return 60000;
            }
            else if (cki.Key == ConsoleKey.D6)
            {
                return 120000;
            }
        }
        else
        {
            SetInterval(Console.ReadKey());
        }
        return 50;
    }

And here is how i execute it within my main class:

        static int interval;

        interval = DefineInterval.SetInterval(Console.ReadKey());
        Console.WriteLine("");
        Console.WriteLine(interval.ToString());

So whats happening now is:

If i press one of the 6 numbers correctly without pressing any other key before, its just fine. The output is normal and as it's supposed to be.

Then again, when i press, for example "a6" on my Keyboard all i get is:

" a6 50 "

Any ideas? Also probably not the best way to do such a thing.


Solution

  • The recursive call to SetInterval in the else block doesn't do anything with the return value. What you want is this:

    public static Int32 SetInterval(ConsoleKeyInfo cki)
    {
        if (cki.Key == ConsoleKey.D1)
        {
            return 10000;
        }
        else if (cki.Key == ConsoleKey.D2)
        {
            return 20000;
        }
        else if (cki.Key == ConsoleKey.D3)
        {
            return 30000;
        }
        else if (cki.Key == ConsoleKey.D4)
        {
            return 45000;
        }
        else if (cki.Key == ConsoleKey.D5)
        {
            return 60000;
        }
        else if (cki.Key == ConsoleKey.D6)
        {
            return 120000;
        }
        else
        {
            return SetInterval(Console.ReadKey());
        }
    }
    

    Note that I also moved the unnecessary if statement surrounding the first else if chain.