如何将 Console.Readkey 转换为 int c#

2024-06-28

我正在尝试将用户输入键转换为 int,用户将输入 1 到 6 之间的数字。

这是我到目前为止在方法中所拥有的,它不起作用,但抛出格式异常未得到处理。

        var UserInput = Console.ReadKey();



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

        Console.WriteLine(Bowl);

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

    }

简单地说您正在尝试转换System.ConsoleKeyInfo to an int.

在你的代码中,当你调用UserInput.ToString()你得到的是表示当前对象的字符串,不是控股value or Char正如你所期望的。

为了获得控股权Char as a String您可以使用UserInput.KeyChar.ToString()

此外,您必须检查ReadKey for a digit在你尝试使用之前int.Parse方法。因为Parse当无法转换数字时,方法会抛出异常。

所以它看起来像这样,

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
}

和你的代码:

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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 Console.Readkey 转换为 int c# 的相关文章

随机推荐