static int beverageSelection()
{
Console.WriteLine();
int brand;
string _val = "";
Console.Write("Enter number: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
brand = Convert.ToInt32(Console.ReadLine());
return brand;
}
上述方法令我头疼。我无法弄清楚如何告诉控制台应用程序它不应该让我输入任何字符甚至是输入按钮,直到我在控制台中输入一个数字。然后,只有这样我才能按Enter键。 无论如何,这个程序是我为了好玩而创建的自动售货机,我不完全理解这段代码中的do while循环只是为了清楚。
答案 0 :(得分:4)
使用Console.ReadLine
代替Console.ReadKey
:
int brand = 0;
while (true)
{
string val = Console.ReadLine();
if (int.TryParse(val, out brand)) break;
}
答案 1 :(得分:3)
改进原始代码以显示并仅接受数字
static void Main(string[] args)
{
Console.WriteLine();
int brand;
string _val = "";
Console.Write("Enter number: ");
while(true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && int.TryParse(_val, out brand))
{
Console.WriteLine();
break;
}
if (key.Key != ConsoleKey.Backspace)
{
int val;
if (int.TryParse(key.KeyChar.ToString(), out val))
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (_val.Length > 0)
{
_val = _val.Substring(0, _val.Length - 1);
Console.Write("\b \b");
}
}
}
Console.WriteLine("Brand: {0}", brand);
Console.ReadKey();
}
答案 2 :(得分:2)
为了完整起见,如果有人希望控制台在选择数字值之前阻止非数字字符,您只需使用此无用代码即可完成任务:
int inputBoundary = Console.CursorLeft;
string consoleInput = String.Empty;
ConsoleKeyInfo inputKey;
while((inputKey = Console.ReadKey(true)).Key != ConsoleKey.Enter || consoleInput == String.Empty)
{
if (inputKey.Key == ConsoleKey.Backspace && Console.CursorLeft != inputBoundary)
{
Console.Write("\b \b");
consoleInput = consoleInput.Remove(consoleInput.Length - 1);
continue;
}
if (Char.IsNumber(inputKey.KeyChar))
{
Console.Write(inputKey.KeyChar);
consoleInput += inputKey.KeyChar;
}
}
int selection = Int32.Parse(consoleInput);