简单地说,您正在尝试转换System.ConsoleKeyInfo
为int
.
在您的代码中,当您调用时UserInput.ToString()
,您得到的是代表当前对象的字符串,而不是持有value
或Char
您期望的。
要获得控股权Char
,String
您可以使用UserInput.KeyChar.ToString()
此外,您必须在尝试使用方法之前检查ReadKey
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();
}