How do I detect a specific word in C#

Viewed 440

I am not a coder or anything I am a noob at coding. I tried to do Console.ReadLine("stop") then Console.End but it doesn't work.

Console.WriteLine("What's your name?");
Console.ReadLine();

Console.WriteLine("Cool! My Name Is Program Bot!");
Console.ReadLine("stop");
Console.End();
3 Answers

You need to assign to a variable and then check with conditionals

        Console.WriteLine("What's your name?");
        Console.ReadLine();

        Console.WriteLine("Cool! My Name Is Program Bot!");
        var output = Console.ReadLine();
        if (output == null || output == "stop") {
            Environment.Exit(0);
        }

You need to check the following items in to understand what's what:

if/else statements -> Is how your code decides how to do something.

c# variables -> var output is a variable declaration which could also be string output

c# methods -> Console.ReadLine() is a method that returns a string value

if you are interested in having the app continue until you ask it to stop, you can put everything in a "while" loop like this:

bool reachedEnd = false;

while (!reachedEnd) {
    Console.WriteLine ("What's your name?");
    string name = Console.ReadLine ();

    Console.WriteLine ("Cool! My Name Is Program Bot!");
    string endQuestion = Console.ReadLine ();
    if (endQuestion == "stop") {
        reachedEnd = true;
    }
}

in 99% of the cases there is not need to have:

Environment.Exit(0);

because after the loop is finished there won't be any code left to execute so it will either exit or just hang until you close it yourself or with additional press of a key. but you want it to close completely, you can add that after the loop and when the loop is finished it will terminate the app.

bool reachedEnd = false;

while (!reachedEnd) {
    Console.WriteLine ("What's your name?");
    string name = Console.ReadLine ();

    Console.WriteLine ("Cool! My Name Is Program Bot!");
    string endQuestion = Console.ReadLine ();
    if (endQuestion == "stop") {
        reachedEnd = true;
    }
}

Environment.Exit(0);

You can use while and until user do not enter stop your program is working.

class Program
{
    static void Main(string[] args)
    {
        string text = string.Empty;
        while (text != "stop")
        {
            Console.WriteLine("What's your name?");
            Console.ReadLine();
            Console.WriteLine("Cool! My Name Is Program Bot!");
            text = Console.ReadLine();
        }
    }
}
Related