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

走远了吗. 提交于 2019-12-05 14:56:32

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();
}

Similarly:

ConsoleKeyInfo info = Console.ReadKey();
int val;
if (int.TryParse(info.KeyChar.ToString(), out val))
{
    Console.WriteLine("You pressed " + val.ToString());
}

Here is an extension class that makes it a little more extensible and not just for integers:

using System;

/// <summary>
/// Extension methods for <see cref="ConsoleKeyInfo"/>
/// </summary>
public static class ConsoleKeyInfoExtensions
{
    /// <summary>
    /// Attempts to cast the <see cref="ConsoleKeyInfo.KeyChar"/> value from the <paramref name="instance"/> to <typeparamref name="T"/>.
    /// </summary>
    /// <typeparam name="T">The generic type to cast to.</typeparam>
    /// <param name="instance">The <see cref="ConsoleKeyInfo"/> to extract the value from</param>
    /// <returns>Returns the value in the <see cref="ConsoleKeyInfo.KeyChar"/> as <typeparamref name="T"/></returns>
    /// <exception cref="InvalidCastException">If there is an issue with the casting.  For example, boolean is not valid.</exception>
    /// <exception cref="ArgumentNullException">If the <paramref name="instance"/> is null.</exception>
    public static T GetValue<T>(this ConsoleKeyInfo instance)
    {
        if (instance == null)
            throw new ArgumentNullException(nameof(instance));

        var stringValue = instance.KeyChar.ToString();

        try
        {
            return (T)Convert.ChangeType(stringValue, typeof(T));
        }
        catch
        {
            throw new InvalidCastException($"Unable to cast a {nameof(ConsoleKeyInfo.KeyChar)} to a type of {typeof(T).FullName}.");
        }
    }
}

~ Cheers

There are ConsoleKeys for numerical values. ConsoleKey.D5 is for 5.

The block of code can be re-written as -

var bowl = -1;
var userInput = Console.ReadKey();
if(userInput.Key == ConsoleKey.D5)
{
  bowl = 5; 
}

Here's the short answer without error checking.

int.Parse(Console.ReadKey().KeyChar.ToString());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!