0

I've only had limited coding experience and i need help with my code. I want it when a user types "Y" or "N" the program is able to react accordingly to your decision and display a text response. It would really help if it was explained clearly and dumbed down.

Thanks

W.Simmons
  • 11
  • 1
  • 1

4 Answers4

1

Take a look at the MSDN Console.ReadLine examples here.

Also Console.ReadKey might be useful.

Console.ReadLine usage looks like this:

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();
   }
}
x5657
  • 1,172
  • 2
  • 13
  • 26
1

As the PO seem to want y/n key Hit I would suggest Console.ReadKey() rather than Console.ReadLine() as the later needs an extra entering. KeyChar Property of the ConsoleKeyInfo gives the character user entered.

var x = Console.ReadKey().KeyChar;
    if(x=='y'||x=='Y')
    {
    //do something
    }
    else if(x=='n'||x=='N')
    {
    //do something else
    }
Jins Peter
  • 2,368
  • 1
  • 18
  • 37
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Nahuel Ianni May 03 '17 at 09:08
  • How about now.? Do you want to vote me up.?? – Jins Peter May 03 '17 at 09:16
1

If you use a console you can use the 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");
}
Raz Zelinger
  • 686
  • 9
  • 24
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;
        }
    }
}
Marius Orha
  • 670
  • 1
  • 9
  • 26