简体   繁体   English

为什么我的简单C#程序立即退出?

[英]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. 我刚开始学习C#,并且正在解决一个需要读取名称列表(由用户输入)并再次打印出来的问题。 I should accept up to 20 names. 我最多可以接受20个名字。 If the user enters null or QUIT, I should stop taking names. 如果用户输入null或QUIT,则应停止使用名称。

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. 您将数组声明为20个名称...没问题。

Then you have your for loop STARTING with a value of 20 which is already AT the length of the arrays. 然后,您的for循环STARTING的值为20,该值已经是数组长度的AT。 Start your loop with 0. 从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. 我使用了一个字符串列表来存储用户输入,并在'maxname'为20之后编写了它。

Add

Console.ReadLine();

At the end after the for loop. 在for循环之后结束。

It auto closes when it finishes. 完成后会自动关闭。 By adding Console.ReadLine(); 通过添加Console.ReadLine(); at the end it will instruct it remain open 最后会指示它保持打开状态

The problem is in your for loop: 问题出在您的for循环中:

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

You initialize maxNames to 20, and then iterate as long as maxNames < names.Length . 您将maxNames初始化为20,然后进行迭代,只要maxNames < names.Length From string[] names = new string[20]; 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 . 我们知道names.Length20 ,所以在第一次迭代之前条件的计算结果为20 < 20 ,当然是false Thus, the loop is never entered and the program exits. 因此,永不进入循环,程序退出。 You probably meant to initialize maxNames to 0 , not 20 . 您可能打算将maxNames初始化为0 ,而不是20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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