に変換しようとしているだけSystem.ConsoleKeyInfo
ですint
。
あなたのコードでは、呼び出すと、現在のオブジェクトを表す文字列UserInput.ToString()
が得られますが、保持または期待どおりではありません。value
Char
あなたが使用できるように保持を取得するにChar
はString
UserInput.KeyChar.ToString()
さらに、メソッドを使用ReadKey
する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();
}