且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从用户获取未知输入并将输入显示回用户?

更新时间:2023-11-14 15:23:40

首先,基于控制台的应用程序的交互式UI是一个很大的矫枉过正,实用。几乎所有实用或良好的仅限控制台的应用程序都不使用交互式用户输入。相反,他们期望在一个命令行中输入所有内容。如果命令行太大,则使用包含所有必需输入的文件名这样的选项。



但是这段代码只是一个有用的练习,你可以做到这一点。首先,在 Console.ReadKey 上隐藏回声:

First of all, interactive UI based on console-only application is a big overkill, to be practical. Nearly all practical, or good, console-only applications don't use interactive user input. Instead, they expect all input in one command line. If command line is too big, such option as the name of the file containing all required input is used.

But it this code is just the useful exercise, you can do it. First of all, hide the echo on Console.ReadKey:
using System;

//...

ConsoleKeyInfo key = Console.ReadKey(true);
// Boolean argument is important here



请参阅:

http ://msdn.microsoft.com/en-us/library/x3h8xffw%28v=vs.110%29.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.consolekeyinfo(v=vs。 110).aspx [ ^ ]。



现在,关键是:不要硬编码密钥和菜单选项文本,特别是如果你是要重复使用它们:在菜单中向用户显示,然后显示用户的选择。您可以执行以下操作:将所有这些信息放入字典中,这将为您提供复杂度为O(1)的搜索。方法如下:


Please see:
http://msdn.microsoft.com/en-us/library/x3h8xffw%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.consolekeyinfo(v=vs.110).aspx[^].

Now, the key is: don't hard-code keys and menu option texts, especially if you are going to re-use them: show to the user in a menu, and then show the user's selection. Here is what you can do: put all this information into a dictionary, which will give you the search with the complexity O(1). Here is how:

using MenuItemDictionary = System.Collections.Generic.Dictionary<char, string>;

//... 

MenuItemDictionary menuItemDictionary = new MenuItemDictionary();

//...

// somewhere in a constructor, populate it:
menuItemDictionary.Add('1', "Please Enter Scores");
menuItemDictionary.Add('1', "..."); // and so on...
// ...

// ...

// Show all options:
foreach(var pair in menuItemDictionary)
    Console.WriteLine("{0}) {1}", pair.Key, pair.Value);

// ...

// This is how you chose the option:
string message;
if (menuItemDictionary.TryGetValue(key.KeyChar, out message)) {
   Console.WriteLine("You have chosen: {0}", message);
   // ...
} else {
   // show something to indicate that this is a wrong key
}



请参阅:

http://msdn.microsoft.com/en-us/library/xfhwa508(v = vs.110).aspx [ ^ ],

http://msdn.microsoft.com/ en-us / library / 5tbh8a42%28v = vs.110%29.aspx [ ^ ]。



现在,消息(菜单选项的文本) )不是全部。你还需要一些行动。该怎么办?而不是使用字符串类型,创建一个组成字符串和操作的类型,它可以是委托实例,具有委托类型,比如 System.Action 。例如:


Please see:
http://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/5tbh8a42%28v=vs.110%29.aspx[^].

Now, the message (text of the menu option) is not all. You also need some action. What to do? Instead of using string type, create a type which composes string and action, which could be a delegate instance, with the delegate type, say, System.Action. For example:

using MenuItemDictionary = System.Collections.Generic.Dictionary<char, MenuItem>;

// ...

class MenuItem {
    internal MenuItem(string name, System.Action action) {
        this.Name = name;
        this.Action = action;
    }   
    internal string Name { get; private set; }
    internal System.Action { get; private set; }
}





然后,用键填充字典, MenuItem 实例,每个实例代表名称和操作。使用键显示名称,如上所示。密钥被识别,显示用户的选择并调用从字典中获取的操作,其值为 MenuItem 类型的值元素。



-SA



And then, populate dictionary with keys, and MenuItem instances, each representing name and action. Show the names with keys as shown above. The the key is recognized, show the choice to the user and call the action both taken from the dictionary in its value element of the type MenuItem.

—SA






你走了我修改了你的代码:)



Hi,

Here you go I have modified your code :)

static void Main(string[] args)
        {
            Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~Menu~~~~~~~~~~~~~~~~~~~~~~");
            Console.WriteLine();
            Console.WriteLine("Please Choose one of the following options");
            Console.WriteLine();
            Console.WriteLine("1) Please Enter Scores ");
            Console.WriteLine("2) Display Scores ");
            Console.WriteLine("3) Calculate Statistics  ");
            Console.WriteLine("4) Exit Program ");


            int menuselect;
            int[] userScore;

            userScore = new int[0];
            menuselect = 0;

            while (menuselect != 4)
            {
                Console.Write(Environment.NewLine + " Please input your choice : ");
                 menuselect = Convert.ToInt32(Console.ReadLine());
                 Console.WriteLine();
                if (menuselect == 1)
                {

                    // Enter Scores
                    // int ScoresOpt1 = First set of user input scores
                    Console.WriteLine("How many Scores would you like to Enter?   ");
                    int ScoresOpt1 = Convert.ToInt32(Console.ReadLine());
                    userScore = new int[ScoresOpt1];
                    for (int i = 0; i < ScoresOpt1; ++i)
                    {
                        Console.Write(" Score[" + i.ToString() + "] = ");
                        userScore[i] = Convert.ToInt32(Console.ReadLine());
                        //Console.WriteLine(userScore);
                    }
                    Console.WriteLine("Scores are saved");
                    //Console.ReadKey();
                }
                else if (menuselect == 2)
                {
                    //Display Scores

                    if (userScore.Length == 0)
                        Console.WriteLine("Save some score first");
                    else
                    {
                        Console.WriteLine("Your Scores are listed below:    ");
                        int i = 0;
                        foreach (int scr in userScore)
                            Console.WriteLine(" Score[" + (i++).ToString() + "] = " + scr.ToString());
                    }

                    //Console.ReadKey();
                }
                else if (menuselect == 3)
                {
                    // Option 3 code goes here
                    Console.WriteLine("I will calculate your scores for you below:   ");
                    //write your logic
                    //Console.ReadKey();
                }
                else if (menuselect == 4)
                {
                    //Option 4 code goes here
                    Console.WriteLine("Press any key to close the program");
                    Console.ReadKey();

                }
                else
                {
                    // Any other option besides one listed in the menu
                    Console.WriteLine("Hey!!! You must not know how to follow directions!!!!!!! :|");
                    Console.WriteLine();
                }



                // Display new menu! woot!
                if (menuselect != 4)
                {
                    Console.WriteLine();
                    Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~Menu~~~~~~~~~~~~~~~~~~~~~~");
                    Console.WriteLine();
                    Console.WriteLine("Please Choose one of the following options");
                    Console.WriteLine();
                    Console.WriteLine("1) Please Enter Scores ");
                    Console.WriteLine("2) Display Scores ");
                    Console.WriteLine("3) Calculate Statistics  ");
                    Console.WriteLine("4) Exit Program ");
                }

            }


            //Console.ReadKey();

        }





并感谢Jake因为你我很长一段时间以来一直在控制台上工作我喜欢在控制台上工作:)



and thanks Jake because of you I have worked on console after a long time I love to work on console :)


使用do ... while循环和切换案例以使你的程序有效
use do...while loop and switch case to make your program effective