Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

visual studio - How do I make my program accept nothing but uppercase letters in C#?

This is a C# question. I want to make my program accept nothing but uppercase letters. I have managed to make it reject lowercase letters but I don't know how to make it reject numbers and other characters. Thank you for your help!

#region Question3
    /* Write an application named EnterUppercaseLetters that asks the user
     * to type an uppercase letter from the keyboard. If the character entered 
     * is an uppercase letter, display OK; if it isn't an uppercase letter, 
     * display an error message. The program continues until the user types an exclamation point.
     */
static void  EnterUppercaseLetters()
    {
        //char letter;
        bool toContinue = true;
        do
        {
            Console.Write("Enter an uppercase letter: ");
            //string input = Console.ReadLine();
            char letter = Convert.ToChar(Console.ReadLine());
            //double number = Convert.ToDouble(input);
            //int number = Convert.ToInt32(letter);
            if (letter == '!')
            {
                toContinue = false;
            }
            else
            {
                if (letter == Char.ToUpper(letter))
                {
                    Console.WriteLine($"{letter} OK");
                }
                else
                {
                    Console.WriteLine("ERROR!");
                    continue;
                }
            }
        } while (toContinue);
        Console.WriteLine();
    }

#endregion

question from:https://stackoverflow.com/questions/65545562/how-do-i-make-my-program-accept-nothing-but-uppercase-letters-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@Moe - what you've got is good ... but maybe you'd prefer not entering the whole line. You can try something like this instead:

static void Main(string[] args)
{
    char ch;
        
    //input character 
    Console.WriteLine("Enter an UPPER CASE character, or '!' to exit: ");
    while ((ch = Console.ReadKey().KeyChar() != '!')
    {
       if (IsUpper(ch))
            Console.WriteLine("Input character is {0}: OK", ch);
       else 
            Console.WriteLine("Input character is {0}: ERROR!", ch);
    }
}

This will respond immediately when you enter ANY keystroke. It will exit immediately when you type "!". And it will print "OK" (for an upper case character) or "ERROR!" otherwise.

Relevant documentation (for our peripatetic friend Jeppe Stig Nielsen):


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...