Question

I have this code here:

    string code1 = null;
    Console.Write("Username: " + Environment.UserName.ToString() + ">");
    string line = Console.ReadLine();
    if (line == "info")
    {
        Console.WriteLine("Info:");
    }
    else if (line == "Set Code")
    {
        if (code1 == null)
        {
            Console.Write("TEST");
        }
        else
        {
            Console.WriteLine("'Set Code' is not known as a command \nEnter 'info' to view all commands");
            Console.Write("Username: " + Environment.UserName.ToString() + ">");
        }
    }
    else
    {
        Console.WriteLine("'" + line + "' is not known as a command \nEnter 'info' to view all commands");
    }
    Console.ReadLine();

When I type something in, like "null", then it will run the else code. If I try to type something in again, then it closes the console. Why does it do that?

Was it helpful?

Solution

If you were to put the code into a while loop, it will not close. Here is the edited code:

string code1 = null;
while(true)
{
    Console.Write("Username: " + Environment.UserName.ToString() + ">");
    string line = Console.ReadLine();
    if (line == "info")
    {
        Console.WriteLine("Info:");
    }
    else if (line == "Set Code")
    {
        if (code1 == null)
        {
            Console.Write("TEST");
        }
        else
        {
            Console.WriteLine("'Set Code' is not known as a command \nEnter 'info' to view all commands");
            Console.Write("Username: " + Environment.UserName.ToString() + ">");
        }
    }
    else if (line == "quit")
    {
        break;
    }
    else
    {
        Console.WriteLine("'" + line + "' is not known as a command \nEnter 'info' to view all commands");
    }
}

OTHER TIPS

Your first ReadLine() will wait for user input as you noticed. You type "null" and it enters the

else
{
    Console.WriteLine("'" + line + "' is not known as a command \nEnter 'info' to view all commands");
}

control flow.

When you reach the second ReadLine(), you can type anything but when you do so and type enter, the program has nothing else to do and therefore exits.

You should try making a loop if you want a never ending input.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top