[英]How do I convert a Console.Readkey to an int c#
我正在嘗試將用戶輸入鍵轉換為 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
轉換為int
。
在您的代碼中,當您調用UserInput.ToString()
,您得到的是表示當前 object的字符串,而不是您期望的持有value
或Char
。
要將持有的Char
作為String
您可以使用UserInput.KeyChar.ToString()
此外,在嘗試使用int.Parse
方法之前,您必須檢查ReadKey
中的digit
。 因為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();
}
相似地:
ConsoleKeyInfo info = Console.ReadKey();
int val;
if (int.TryParse(info.KeyChar.ToString(), out val))
{
Console.WriteLine("You pressed " + val.ToString());
}
這是一個擴展類,它使它更具可擴展性,而不僅僅是整數:
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}.");
}
}
}
~干杯
有用於數值的 ConsoleKeys。 ConsoleKey.D5 為 5。
代碼塊可以重寫為 -
var bowl = -1;
var userInput = Console.ReadKey();
if(userInput.Key == ConsoleKey.D5)
{
bowl = 5;
}
這是沒有錯誤檢查的簡短答案。
int.Parse(Console.ReadKey().KeyChar.ToString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.