using System;
using System.Text;
namespace 判断输入是否为数字
{
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
char temp = Console.ReadKey().KeyChar;
if (char.IsDigit(temp))
{
news[i] = temp;
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}
}
此ConsoleApp假设要从Console输入年,月,日。我要禁用数字(0-9)以外的键。
现在,这是我的代码,通常可以使用。
但是,例如,我想输入“ 2020”到年份,当我输入“ 202”并按Enter时,光标将跳到该行的开头。看起来像屏幕截图,尽管不会影响最终结果。
我想让控制台忽略Enter键(什么都没发生,请怎么做?
这是跳过输入键的方法
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
var key = Console.ReadKey();
if (key.KeyChar.IsDigit(temp))
{
news[i] = temp;
}
else if(key == ConsoleKey.Enter)
{
// ignore
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}