Multiple IFs won't work

98 Views Asked by At

I'm creating a Desktop application (console) for Windows, using C#.

This is my code:

namespace myapp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello!");
            Console.WriteLine("Type 'exit' to exit!");
            string line = Console.ReadLine();
            if (line == "exit") {
                Environment.Exit(0);
            }
            if (line == "copyright") {
                Console.WriteLine("Copyright 2017 TIVJ-dev");
            }
        }
    }
}

If I type "exit", it works fine (I'm sure it does this Environment.Exit(0); action). But if I type "copyright", it does not work. I can see an empty line instead. I started with C# today, so my apologies if this is very beginner problem. I haven't found solution on the internet.

Screenshot:

Copyright command is not doing anything

4

There are 4 best solutions below

5
On BEST ANSWER

You could use an else if statement;

   namespace myapp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello!");
            Console.WriteLine("Type 'exit' to exit!");
            string line = Console.ReadLine();
            if (line == "exit")
            {
                Environment.Exit(0);
            }
            else if (line == "copyright") {
                Console.WriteLine("Copyright 2017 TIVJ-dev");
            }
        }
    }
}

Edit

By using an if/else this does the same as using multiple if statements however this is a more efficient way and make it easier when using break points.

2
On

I'm not sure in what way it doesn't work. It should run

Console.WriteLine("Copyright 2017 TIVJ-dev");

then immediately close the console window. Try putting another

Console.ReadLine();

at the end of Main().

0
On

Try launching the application by pressing ctrl F5 in visual studio and seeing if it works. Alternatively click on debug->start without debugging.

Then write "copyright" and press enter.

What is probably happening is that the console is printing the line, then closing before you have a chance to see it. When you don't use the debugger the console stays open even once the application is finished.

0
On

Now everyone: Now this project works fine! Thanks for people who said add another Console.ReadLine. When I tested else if, I forgot there was that also. But now it works, so I try to close this. Thanks everyone!