简体   繁体   中英

Restricting user input to numbers only

Brand new to C# [4 hours new :)], but hoping for some pointers on a Board Feet Calculator restricting the user input to only numbers, not allow letters or special characters.

First, does the restriction take place in the Class, Method, and/or Program? (I believe Class and Method)

Second, I've seen an example below, would I use something similar to this?

Third, if so, do I need to make separate classes for KeyPress and KeyPressEventArgs? (I believe they automatically there eg public char KeyChar { get; set; }

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // allows only letters
    if (!char.IsLetter(e.KeyChar))
    {
        e.Handled = true;
    }
}

My Program

namespace BoardFt_MyTry_
{
    class Program
    {
        static void Main(string[] args)
        {
            Board board = new Board();

        board.lengthOfboard = Convert.ToDouble(askQuestion("What is the length of your board in inches?"));
        board.widthOfboard = Convert.ToDouble(askQuestion("What is the width of your board in inches?"));
        board.thicknessOfboard = Convert.ToDouble(askQuestion("What is the thickness of your board in inches?"));

        Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());

        Console.ReadLine();
    }
    private static string askQuestion(string question)
    {
        Console.WriteLine(question);
        return Console.ReadLine();
    }

}

My Board Class

namespace BoardFt_MyTry_
{
    class Board
    {
        public double lengthOfboard;
        public double widthOfboard;
        public double thicknessOfboard;

    public double CalcBoardFt()
    {
        double boardft = 0;

        boardft = (this.lengthOfboard * this.widthOfboard * this.thicknessOfboard) / 144;

        return boardft;
    }
}
}

You can't really do that in a console application. All you can do is allow the user to input the bad data, then tell the user that the data is bad.

You can try something like this:

class Program
{
    public double AskDnoubleQuestion(string message){
        do {
        Console.Write(message);
        var input = Console.ReadLine();

        if (String.IsNullOrEmpty(input)){
            Console.WriteLine("Input is required");
            continue;
         }
         double result;
         if (!double.TryParse(input, out result)){
           Console.WriteLine("Invalid input - must be a valid double");
           continue;
         }
         return result;
    }

    static void Main(string[] args)
    {
        Board board = new Board();

    board.lengthOfboard = AskDoubleQuestion("What is the length of your board in inches?");
    board.widthOfboard = AskDoubleQuestion(askQuestion("What is the width of your board in inches?");
    board.thicknessOfboard = AskDoubleQuestion(askQuestion("What is the thickness of your board in inches?");

    Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());

    Console.ReadLine();
}

In case validation is not the way you want to proceed, you could do something like this:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number:");

        string number = ReadNumber();
        Console.WriteLine("You entered: " + number);
    }

    private static string ReadNumber()
    {
        string input = "";

        do
        {
            ConsoleKeyInfo keyInfo = Console.ReadKey(true);
            if (char.IsNumber(keyInfo.KeyChar))
            {
                input = input + keyInfo.KeyChar;
                Console.Write(keyInfo.KeyChar);
            }
            if (keyInfo.Key == ConsoleKey.Enter)
            {
                Console.WriteLine();
                break;
            }
            if (keyInfo.Key == ConsoleKey.Backspace)
            {
                input = input.Substring(0, input.Length - 1);
                Console.Write("\b \b");
            }
        } while (true);

        return input;
    }
}

This will allow the user to enter only numbers. You could filter it anyway you want, if you wanted to. For example, only letters and numbers, etc...

As it stands right now, it only allows integer numbers. If you want to allow a decimal point, change the line above to this: if (char.IsNumber(keyInfo.KeyChar) || keyInfo.KeyChar == '.')

You could write a method that reads key by key (not displaying in the console), ignores non-numeric characters, prints valid characters and appends them to a StringBuilder instance, like so:

public static string ReadOnlyNumbers()
{
    StringBuilder input = new StringBuilder();
    ConsoleKeyInfo ckey;

    while ((ckey = Console.ReadKey(true)).Key != ConsoleKey.Enter)
    {
        if (Char.IsDigit(ckey.KeyChar))
        {
            Console.Write(ckey.KeyChar);
            input.Append(ckey.KeyChar);
        }

        if (ckey.Key == ConsoleKey.Backspace)
        {
            input.Length--;
            Console.Write("\b \b");
        }
    }

    Console.Write(Environment.NewLine);
    return input.ToString();
}

You could then use it like this:

string input = ReadOnlyNumbers();
Console.WriteLine(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM