Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Console.Readkey to an int c#

I am trying to convert a user input key to an int, the user will be entering a number between 1 and 6.

This is what i have so far sitting inside a method, its not working, yet throwing a format exception was unhandled.

        var UserInput = Console.ReadKey();



        var Bowl = int.Parse(UserInput.ToString());

        Console.WriteLine(Bowl);

       if (Bowl == 5)
        {
            Console.WriteLine("OUT!!!!");
        }
        else
        {
            GenerateResult();
        }

    }
like image 271
astro8891 Avatar asked Mar 10 '15 02:03

astro8891


People also ask

What does the line console ReadKey () do?

ReadKey() Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window.

What is difference between ReadLine and ReadKey in C#?

Difference between ReadLine(), Read(), ReadKey() in C# As MSDN is actually pretty clear. Reads the next line of characters from the standard input stream. simply you can say, it read all the characters from user input. (and finish when press enter).

What is ConsoleKeyInfo?

The ConsoleKeyInfo object describes the ConsoleKey constant and Unicode character, if any, that correspond to the pressed console key.


1 Answers

Simply said you are trying to convert System.ConsoleKeyInfo to an int.

In your code, when you call UserInput.ToString() what you get is the string that represents the current object, not the holding value or Char as you expect.

To get the holding Char as a String you can use UserInput.KeyChar.ToString()

Further more ,you must check ReadKey for a digit before you try to use int.Parse method. Because Parse methods throw exceptions when it fails to convert a number.

So it would look like this,

int Bowl; // Variable to hold number

ConsoleKeyInfo UserInput = Console.ReadKey(); // Get user input

// We check input for a Digit
if (char.IsDigit(UserInput.KeyChar))
{
     Bowl = int.Parse(UserInput.KeyChar.ToString()); // use Parse if it's a Digit
}
else
{
     Bowl = -1;  // Else we assign a default value
}

And your code :

int Bowl; // Variable to hold number

var UserInput = Console.ReadKey(); // get user input

int Bowl; // Variable to hold number

// We should check char for a Digit, so that we will not get exceptions from Parse method
if (char.IsDigit(UserInput.KeyChar))
{
    Bowl = int.Parse(UserInput.KeyChar.ToString());
    Console.WriteLine("\nUser Inserted : {0}",Bowl); // Say what user inserted 
}
else
{
     Bowl = -1;  // Else we assign a default value
     Console.WriteLine("\nUser didn't insert a Number"); // Say it wasn't a number
}

if (Bowl == 5)
{
    Console.WriteLine("OUT!!!!");
}
else
{
    GenerateResult();
}
like image 98
Kavindu Dodanduwa Avatar answered Sep 24 '22 21:09

Kavindu Dodanduwa