C# 如何在输入值之前阻止用户按enter键?
我正在构建一个控制台计算器程序,它需要用户输入两个值来进行数学运算。该应用程序非常全面,但我想限制跳过输入数字的能力C# 如何在输入值之前阻止用户按enter键?,c#,.net,console,calculator,C#,.net,Console,Calculator,我正在构建一个控制台计算器程序,它需要用户输入两个值来进行数学运算。该应用程序非常全面,但我想限制跳过输入数字的能力 Console.WriteLine("Insert a number for value 1: "); string value1 = "0"; ConsoleKeyInfo key; do { key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace) { dou
Console.WriteLine("Insert a number for value 1: ");
string value1 = "0";
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)
{
value1 += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && value1.Length > 0)
{
value1 = value1.Substring(0, (value1.Length - 1));
Console.Write("\b \b");
}
}
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
//parsed here if entered correctly
Double x;
Double parsedVariable = 0;
if (Double.TryParse(value1, out x))
{
Console.WriteLine("You have entered " + x);
Console.Clear();
}
人们会犯错误,有时甚至故意让程序失败。作为程序员,你的工作之一就是编写代码,这样错误和恶意就不会导致程序失败 您无法阻止用户犯错误。但是,您可以编写代码,使其能够容忍错误 特别是,试图阻止用户输入他不应该输入的内容的整个想法比让用户输入任何内容然后检查要困难得多,也不友好得多。例如,上面的代码表面上是“帮助”用户输入有效的浮点数,实际上是一个障碍 假设用户输入了“78.369”。但后来他意识到他应该输入“0.78369”。所以他点击Home键(什么?你的编辑器不支持Home键?假设它支持,因为它应该支持),意思是键入“0”,然后向前箭头两个空格以删除句点。这是一个非常合理的做法,但您的代码不允许用户这样做 它对用户更友好,也更容易编码,允许用户利用控制台的所有编辑功能(比如它们),然后检查用户的全部输入。比如:
string userInput;
double parsedValue;
bool valueIsGood;
do
{
Console.Write("Enter the first value: ");
userInput = Console.ReadLine();
userInput = userInput?.Trim(); // get rid of leading and trailing spaces
valueIsGood =
string.IsNullOrEmpty(userInput) == false
&& double.TryParse(userInput, out parsedValue);
if (!valueIsGood)
{
Console.WriteLine("You must enter a number.");
}
while (!valueIsGood);
有一个特定的理由不使用ReadLine来代替它吗?@Steve说了什么。您只需检查
Console.ReadLine
是否返回null、空或空白。