如何在我的C#控制台应用程序中仅允许数字输入?

13
Console.WriteLine("Enter the cost of the item");                           
string input = Console.ReadLine();
double price = Convert.ToDouble(input);

你好,我希望禁用键盘上的字母A-Z、括号、问号等等。如果输入这些字符,不希望它们在控制台上显示出来。只想要数字1-9显示出来。这是C#控制台应用程序。感谢您的帮助!

7个回答

15

尝试这段代码片段

string _val = "";
Console.Write("Enter your value: ");
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");
        }
    }
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Value You entered is : " + _val);
Console.ReadKey();

1
我修改了一些网络上的代码以满足你的需求。无论如何,欢迎来到StackOverFlow! - John Woo
2
我回头看了一下,它帮助我理解另一个问题。随着我学习更多的C#,我理解了你所做的事情。但在完全理解这个之前,我还有很长的路要走! - Sarah
@491243 我测试了你的简洁代码片段。为了使它按照你的意图正常工作,必须在结尾处跟随 Console.WriteLine();。起初我错过了这一点,花了我一个小时才弄清楚出了什么问题。不错的代码! - aspiring
1
你可以通过添加一些额外的注释来改进这个答案,以帮助解释你的代码如何运作以及为什么要这样做。虽然我最终是通过尝试才弄明白它的,但仍然...例如,Console.ReadKey(true);中布尔参数值为true是必要的,以防止其他按键被显示出来。 - rory.ap

4

过了一会儿,我找到了一个非常简短的解决方案:

double number;
Console.Write("Enter the cost of the item: ");
while (!double.TryParse(Console.ReadLine(), out number))
{
   Console.Write("This is not valid input. Please enter an integer value: ");
}

Console.Write("The item cost is: {0}", number);                          

再见!


3

这篇MSDN文章介绍了如何在控制台窗口中逐个读取字符。使用Char.IsNumber()方法测试每个输入的字符,并拒绝未通过测试的字符。


1
这里有一种方法。如果你刚开始学习C#,它可能会过度设计,因为它使用了一些更高级的语言特性。无论如何,我希望您觉得它很有趣。
它具有一些不错的特点:
  • ReadKeys 方法采用任意函数来测试迄今为止的字符串是否有效。这使得每当你想要从键盘获取过滤后的输入(例如字母或数字但没有标点符号)时,都可以轻松重用它。

  • 它应该能处理任何可以解释为double的内容,例如“-123.4E77”。

然而,与John Woo的答案不同,它无法处理退格键。
以下是代码:
using System;

public static class ConsoleExtensions
{
    public static void Main()
    {
        string entry = ConsoleExtensions.ReadKeys(
            s => { StringToDouble(s) /* might throw */; return true; });

        double result = StringToDouble(entry);

        Console.WriteLine();
        Console.WriteLine("Result was {0}", result);
    }

    public static double StringToDouble(string s)
    {
        try
        {
            return double.Parse(s);
        }
        catch (FormatException)
        {
            // handle trailing E and +/- signs
            return double.Parse(s + '0');
        }
        // anything else will be thrown as an exception
    }

    public static string ReadKeys(Predicate<string> check)
    {
        string valid = string.Empty;

        while (true)
        {
            ConsoleKeyInfo key = Console.ReadKey(true);
            if (key.Key == ConsoleKey.Enter)
            {
                return valid;
            }

            bool isValid = false;
            char keyChar = key.KeyChar;
            string candidate = valid + keyChar;
            try
            {
                isValid = check(candidate);
            }
            catch (Exception)
            {
                // if this raises any sort of exception then the key wasn't valid
                // one of the rare cases when catching Exception is reasonable
                // (since we really don't care what type it was)
            }

            if (isValid)
            {
                Console.Write(keyChar);
                valid = candidate;
            }        
        }    
    }
}

您也可以实现一个IsStringOrDouble函数,它返回false而不是抛出异常,但我将其留作练习。

另一种扩展方式是让ReadKeys接受两个Predicate<string>参数:一个用于确定子字符串是否表示有效条目的开头,另一个用于确定它是否完成。通过这种方式,我们可以允许按键贡献,但在输入完成之前禁止Enter键。这对于像密码输入这样需要确保一定强度或者"是"/"否"输入的情况非常有用。


0

这段代码将允许您:

  • 仅写一个小数点(因为数字只能有一个小数分隔符);
  • 一个减号在开头;
  • 一个零在开头。

这意味着您将无法编写类似于:“00000.5”或“0000...-5”的内容。

class Program
{
    static string backValue = "";
    static double value;
    static ConsoleKeyInfo inputKey;

    static void Main(string[] args)
    {
        Console.Title = "";
        Console.Write("Enter your value: ");

        do
        {
            inputKey = Console.ReadKey(true);

            if (char.IsDigit(inputKey.KeyChar))
            {
                if (inputKey.KeyChar == '0')
                {
                    if (!backValue.StartsWith("0") || backValue.Contains('.'))
                        Write();
                }

                else
                    Write();
            }

            if (inputKey.KeyChar == '-' && backValue.Length == 0 ||
                inputKey.KeyChar == '.' && !backValue.Contains(inputKey.KeyChar) &&
                backValue.Length > 0)
                Write();

            if (inputKey.Key == ConsoleKey.Backspace && backValue.Length > 0)
            {
                backValue = backValue.Substring(0, backValue.Length - 1);
                Console.Write("\b \b");
            }
        } while (inputKey.Key != ConsoleKey.Enter); //Loop until Enter key not pressed

        if (double.TryParse(backValue, out value))
            Console.Write("\n{0}^2 = {1}", value, Math.Pow(value, 2));

        Console.ReadKey();
    }

    static void Write()
    {
        backValue += inputKey.KeyChar;
        Console.Write(inputKey.KeyChar);
    }
}

0

您可以通过以下一行代码来完成:

int n;
Console.WriteLine("Enter a number: ");
while (!int.TryParse(Console.ReadLine(), out n)) Console.WriteLine("Integers only allowed."); // This line will do the trick
Console.WriteLine($"The number is {n}");

如果您想允许使用双精度浮点数而不是整数,您可以将int更改为double等。


-1
        string input;
        double price;
        bool result = false;

        while ( result == false )
            {
            Console.Write ("\n Enter the cost of the item : ");
            input = Console.ReadLine ();
            result = double.TryParse (input, out price);
            if ( result == false )
                {
                Console.Write ("\n Please Enter Numbers Only.");
                }
            else
                {
                Console.Write ("\n cost of the item : {0} \n ", price);
                break;
                }
            }

我想禁用键盘上的字母按钮、括号、问号等。如果您输入这些内容,它将不会显示在控制台中。我只希望数字1-9能够显示出来。但是当前代码没有实现这些功能。 - Rawling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接