简体   繁体   中英

Why does my simple C# program quit immediately?

I'm just starting out learning C#, and I'm working on a problem where I need to read a list of names (input by the user) and print them out again. I should accept up to 20 names. If the user enters null or QUIT, I should stop taking names.

Here's what I've got so far:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[20]; // create a 20 name array
            int nameCount = 0;
            string userInput;
            Console.WriteLine("Enter a bunch of names!"); // ask for a name
            userInput = Console.ReadLine(); // store the name in userInput
            for (int maxNames = 20; maxNames < names.Length; maxNames++)
            {
                if (userInput == "") // if the entry is null, stop taking names.
                {
                    Console.WriteLine("You entered {0}", names);
                    Console.ReadKey();
                }
                else if (userInput == "QUIT") // if the entry is QUIT, stop taking names.
                {
                    Console.WriteLine("You entered {0}", names);
                    Console.ReadKey();
                }
                else // if it isn't null or QUIT, continue populating the array until we hit the max.
                {
                    names[nameCount] = userInput;
                    nameCount = nameCount + 1;
                    maxNames = maxNames + 1;
                }


            }
        }
    }
}

When I run this, I get the "Enter a bunch of names!" prompt, but as soon as I enter a name, the console closes. I'm not sure what I'm doing wrong here. Any help for a newbie is appreciated.

Update: Thanks everybody for all the help. I took a few different pieces of advice (and new shortcuts!) and ended up with this:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[20]; // create a 20 name array
            int nameCount = 0;
            int maxNames = 0;
            Console.WriteLine("Enter a bunch of names!"); // ask for a name
            while (maxNames != 20)
            {
                string userInput = Console.ReadLine(); // store the name in userInput
                if (userInput == "") // if the entry is null, stop taking names.
                {
                    Console.WriteLine("You entered:");
                    foreach (string name in names)
                    {
                        Console.WriteLine(name);
                    }
                    Console.ReadKey();
                }
                else if (userInput == "QUIT") // if the entry is QUIT, stop taking names.
                {
                    Console.WriteLine("You entered:");
                    foreach (string name in names)
                    {
                        Console.WriteLine(name);
                    }
                    Console.ReadKey();
                }
                names[nameCount] = userInput;
                nameCount++;
                maxNames++;
            }
            Console.ReadKey();
        }
    }
}

Welcome to the community. It appears so many are overlooking the very basic loop.

You declared your array to 20 names... No problem.

Then you have your for loop STARTING with a value of 20 which is already AT the length of the arrays. Start your loop with 0.

for (int maxNames = 0; maxNames < names.Length; maxNames++)
{
   // Also, move your input WITHIN the loop
   userInput = Console.ReadLine(); // store the name in userInput

   if (userInput == "") // if the entry is null, stop taking names.
   {
      Console.WriteLine("You entered {0}", names);
      Console.ReadKey();
      break;
   }
   else if (userInput == "QUIT") // if the entry is QUIT, stop taking names.
   {
      Console.WriteLine("You entered {0}", names);
      Console.ReadKey();
      break;
   }
   else 
   // if it isn't null or QUIT, continue populating the array until we hit the max.
   {
      // since maxNames is now properly starting at 0,
      // you don't need your other name counter variable.
      // just use maxNames.  The loop process will increase it next cycle through
      names[maxNames] = userInput;
   }
}

The program ends inmmediately since it doesn't go inside the loop after getting the first input.

static void Main(string[] args)
    {
        List<String> names = new List<string>(); // create a 20 name array
        string userInput;
        int maxNames = 0;
        while (maxNames != 20)
        {
            Console.WriteLine("Enter a bunch of names!"); // ask for a name
            userInput = Console.ReadLine(); // store the name in userInput
            names.Add(userInput);
            maxNames++;
            if(maxNames == 20 || userInput == "" || userInput == "QUIT")
            {
                foreach (string name in names)
                {
                    Console.WriteLine(name);
                }
                Console.ReadKey();
            }
        }
    }

I used a list of strings to store the user inputs, and wrote it after the the 'maxname' has been 20.

Add

Console.ReadLine();

At the end after the for loop.

It auto closes when it finishes. By adding Console.ReadLine(); at the end it will instruct it remain open

The problem is in your for loop:

for (int maxNames = 20; maxNames < names.Length; maxNames++)

You initialize maxNames to 20, and then iterate as long as maxNames < names.Length . From string[] names = new string[20]; we know that names.Length is 20 , though, so before the first iteration the condition evaluates to 20 < 20 , which is, of course, false . Thus, the loop is never entered and the program exits. You probably meant to initialize maxNames to 0 , not 20 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM