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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13106493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:37:21  来源:igfitidea点击:

How do I only allow number input into my C# Console Application?

c#console-application

提问by Sarah

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

Hello, I want the keyboard buttons, A-Z, brackets, question mark, etc to be disabled. I want it so if you type it in, it will not show up in the Console. I only want the numbers 1-9 to show up. This is in C# Console application. Thanks for the help!

您好,我想禁用键盘按钮、AZ、括号、问号等。我想要它,所以如果你输入它,它不会显示在控制台中。我只想显示数字 1-9。这是在 C# 控制台应用程序中。谢谢您的帮助!

采纳答案by John Woo

try this code snippet

试试这个代码片段

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();

回答by Robert Harvey

This MSDN articleexplains how to read characters one at a time in a console window. Test each character as it is input with the Char.IsNumber()method, and reject those characters that fail the test.

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

回答by Matthew Strawbridge

Here is one approach. It's probably overkill if you're just starting out in C#, since it uses some more advanced aspects of the language. In any case, I hope you find it interesting.

这是一种方法。如果您刚开始使用 C#,这可能有点矫枉过正,因为它使用了该语言的一些更高级的方面。无论如何,我希望你觉得它很有趣。

It has some nice features:

它有一些不错的功能:

  • The ReadKeysmethod takes an arbitrary function for testing whether the string so far is valid. This makes it easy to reuse whenever you want filtered input from the keyboard (e.g. letters or numbers but no punctuation).

  • It should handle anything you throw at it that can be interpreted as a double, e.g. "-123.4E77".

  • ReadKeys方法采用任意函数来测试到目前为止的字符串是否有效。这使得在您想要从键盘过滤输入(例如字母或数字但没有标点符号)时很容易重用。

  • 它应该处理你扔给它的任何可以解释为双精度的东西,例如“-123.4E77”。

However, unlike John Woo's answer it doesn't handle backspaces.

但是,与 John Woo 的回答不同,它不处理退格。

Here is the code:

这是代码:

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;
            }        
        }    
    }
}

You also could implement an IsStringOrDoublefunction that returns falseinstead of throwing an exception, but I leave that as an exercise.

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

Another way this could be extended would be for ReadKeysto take two Predicate<string>parameters: one to determine whether the substring represented the start of a valid entry and one the second to say whether it was complete. In that way we could allow keypresses to contribute, but disallow the Enterkey until entry was complete. This would be useful for things like password entry where you want to ensure a certain strength, or for "yes"/"no" entry.

可以扩展的另一种方法是ReadKeys采用两个Predicate<string>参数:一个确定子字符串是否表示有效条目的开始,第二个表示它是否完整。通过这种方式,我们可以允许按键进行贡献,但在Enter输入完成之前不允许按键。这对于您想要确保一定强度的密码输入或“是”/“否”条目非常有用。

回答by Sushrut Bhosale

        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;
                }
            }

回答by Ovidzikas

This code will allow you to:

此代码将允许您:

  • Write only one dot (because numbers can have only one decimal separator);
  • One minus at the begining;
  • One zero at the begining.
  • 只写一个点(因为数字只能有一个小数点分隔符);
  • 一开始减一;
  • 一开始是一个零。

It means that you not be able to write something like: "00000.5" or "0000...-5".

这意味着您不能写出诸如“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);
    }
}

回答by yasserpulido

In a while, I got a solution really short:

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

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);                          

See you!

再见!