【问题标题】:How to detect user input in c# [duplicate]如何在c#中检测用户输入[重复]
【发布时间】:2017-05-03 06:29:39
【问题描述】:

我只有有限的编码经验,我需要有关我的代码的帮助。当用户键入“Y”或“N”时,我希望它能够对您的决定做出相应的反应并显示文本响应。 如果解释清楚并简化,那真的很有帮助。

谢谢

【问题讨论】:

  • 什么样的应用程序。?您正在开发控制台应用程序吗?
  • Console.Readline() ?

标签: c#


【解决方案1】:
class Program
{
    static void Main()
    {
        //read from console
        string userInput = Console.ReadLine();

        //treat read value
        switch(userInput)
        {
            case "Y":
                Console.WriteLine("Y was entered!");
                break;
            case "N":
                Console.WriteLine("N was entered!");
                break;
        }
    }
}

【讨论】:

    【解决方案2】:

    看看MSDN Console.ReadLine examples here

    Console.ReadKey 也可能有用。

    Console.ReadLine 用法如下所示:

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Console.Clear();
    
          DateTime dat = DateTime.Now;
    
          Console.WriteLine("\nToday is {0:d} at {0:T}.", dat);
          Console.Write("\nPress any key to continue... ");
          Console.ReadLine();
       }
    }
    

    【讨论】:

      【解决方案3】:

      如果您使用控制台,您可以使用Console.ReadLine

      string line = Console.ReadLine();
      if (line == "Y")
      {
         Console.WriteLine("Y was pressed");
      }
      else if (line == "N")
      {
         Console.WriteLine("N was pressed");
      }
      else
      {
         Console.WriteLine(line + " was pressed");
      }
      

      【讨论】:

        【解决方案4】:

        由于 PO 似乎需要 y/n 键 Hit,我建议使用 Console.ReadKey() 而不是 Console.ReadLine(),因为后者需要额外输入。 KeyChar ConsoleKeyInfo 的属性给出了用户输入的字符。

        var x = Console.ReadKey().KeyChar;
            if(x=='y'||x=='Y')
            {
            //do something
            }
            else if(x=='n'||x=='N')
            {
            //do something else
            }
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        • 现在怎么样。?你要投票给我吗??
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-26
        • 2016-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        • 1970-01-01
        相关资源
        最近更新 更多