尝试对字符输出控制台程序进行简单用户输入

Trying to make a Simple User input to character output Console program

我已经很认真地研究过了。整数看起来很容易,但这是我一直试图在 visual studio.

中用 C# 弄清楚的东西

我想让用户输入一个像 "a" 这样的字母,然后控制台写入 "apple"、b=bobby、c=charlie 等,当他们不输入字母时然后它会给出类似 "no letters used" 的错误消息。我不确定我是否应该使用 ToChar 将用户输入的字符串转换为字符串,或者最好的方法是什么。我还没有进入数组,也没有弄清楚带有字符(而不是整数或字符串)的切换命令。

我就是这样做的:

Console.WriteLine("Enter a letter ");
choice = Convert.ToChar(Console.ReadLine());

if (char choice = 'a'){
    Console.WriteLine("apple");

}else if (char choice = 'b'{
    Console.WriteLine("bobby");
}else if (char choice = 'b'{
    Console.WriteLine("bobby");
}else (char choise=!IsLetter){
    Console.WriteLine("No Letters entered");

这就是你使用 switch:

的写法
switch (choice){
case 'a':
    Console.WriteLine("apple");
    break;
case 'b':
    Console.WriteLine("bobby");
    break;
case 'c':
    Console.WriteLine("charlie");
    break;
default:
    Console.WriteLine("No Letters entered");
    break;
}

使用 switch 语句,可能最适合您的场景

static void Main(string[] args)
    {
        //initialise bool for loop
        bool flag = false;

        //While loop to loop Menu
        while (!flag)
        {
            Console.WriteLine("Menu Selection");
            Console.WriteLine("Press 'a' for apple");
            Console.WriteLine("Press 'b' for bobby");
            Console.WriteLine("Type 'exit' to exit");

            //Read userinput
            //Store inside string variable
            string menuOption = Console.ReadLine();

            switch (menuOption)
            {
                case "a":
                    //Clears console for improved readability
                    Console.Clear();
                    //"\n" Creates empty line after statement
                    Console.WriteLine("apple has been selected\n");
                    //Break out of switch
                    break;
                case "b":
                    Console.Clear();
                    Console.WriteLine("bobby has been selected\n");
                    break;
                case "exit":
                    Console.Clear();
                    Console.WriteLine("You will now exit the console");
                    //bool set to false to exit out of loop
                    flag = true;
                    break;
                    //Catch incorrect characters with default
                default:
                    Console.Clear();
                    //Error message
                    Console.WriteLine("You have not selected an option\nPlease try again\n\n");
                    break;
            } 
        } 


        Console.ReadLine();

如果你想坚持 if else,你可以这样做:

if (choice == 'a')
{
    Console.WriteLine("apple");
}
else if (choice =='b')
{
    Console.WriteLine("bobby");
}
else if (char choice = 'c')
{
    Console.WriteLine("charlie");
}
else
{
    Console.WriteLine("No Letters entered");
}

你不需要再对你的 else 设置条件:)