简体   繁体   English

如何将用户输入存储到列表中然后输出结果-C#控制台程序

[英]How to store user input into a List then output results - C# console program

How do I store user input into a "List" List<string> ItemList then output whatever was entered? 如何将用户输入存储到“列表” List<string> ItemList然后输出输入的内容?

Currently, when I run the program users can enter values into the varItemInput and the for-loop proceeds until 10 entries have been input, but then instead of outputting the entered values, it outputs 10 empty list values. 当前,当我运行该程序时,用户可以在varItemInput输入值,并且for循环将继续进行,直到输入了10个条目为止,但随后会输出10个空列表值,而不是输出输入的值。 What am I doing wrong? 我究竟做错了什么?

I think the error is, it's not storing the users input into varItemInput and is just outputting the predefined empty List.Add(""); 我认为错误是,它没有将用户输入存储到varItemInput ,而只是输出了预定义的空List.Add(""); values. 价值观。

How would I make a user populated List up to 10 entries? 如何使用户填充的列表最多10个条目?

This is supposed to be like an "Inventory Program" where a user enters an item like a Hammer, then after 10 entries it displays all 10 entries on the output screen. 假定这就像一个“库存程序”,用户在其中输入诸如“锤”之类的项目,然后在输入10次后,将在输出屏幕上显示所有10个项目。

I know how to do this with an array, but this particular program has to be done with a List. 我知道如何使用数组来执行此操作,但是此特定程序必须使用列表来完成。

Here is my code 这是我的代码

using System;
using System.Collections.Generic;

namespace ListProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            string varListInput = null;
            Boolean varIsValid = true;
            Int32 intTime = 3000000;



            while (varIsValid)
            {
                try
                {
                    Console.Clear(); //Clear the console program from any scren values
                    Console.WriteLine("Welcome to OTC CIS120" + "\n");
                    Console.WriteLine("ACME Co. Item Locator List Program" + "\n"); //Header     



                List<string> ItemList = new List<string>();
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");
                ItemList.Add("");

                // Reverse the output to show recent input first.
                ItemList.Reverse();

                for (int i = 0; i < ItemList.Count; i++) // Continue For Loop until i is > List amount.
                {
                    Console.WriteLine(i + ": "+ "Enter Item Name To Add To Inventory"); // Asks for user input into array.
                    varListInput = Console.ReadLine(); // User inputs value into field.

                }

                Console.WriteLine("Items Added To Inventory Are: "); // Outputs List in reverse order. (Recent input first).
                for (int i = 0; i < ItemList.Count; i++)
                {
                    Console.WriteLine(i + ": " + varListInput); // The entered values array output.
                }

                System.Threading.Thread.Sleep(intTime);
            }

            catch (Exception e)
            {
                Console.WriteLine("The Program Has an Error: " + e.Message); // Error message if program encountered an error durring runtime.
                varIsValid = false;
                System.Threading.Thread.Sleep(intTime);
                Environment.Exit(0); //Exit the program
            }
        }
    }
}

} }

You don't need to reserve List items for this, for example if you need to add only 10 items: 您不需要为此保留列表项,例如,如果您仅需要添加10个项:

List<string> ItemList = new List<string>();
Console.WriteLine("Items Added To Inventory Are: "); // Outputs List in reverse order. (Recent input first).
for (int i = 0; i < 10; i++) // Continue For Loop until i is < the needed amount.
{
    Console.WriteLine($"{i+1}: Enter Item Name To Add To Inventory"); // Asks for user input into array.
    var ListInput = Console.ReadLine(); // User inputs value into field.
    ItemList.Add(ListInput);
}

However to replace the value of a list item you can just assign the new value like: 但是,要替换列表项的值,您可以仅分配新值,例如:

ItemList[i] = newStringValue;

In your original post you aren't getting the current item from the list. 在您的原始帖子中,您没有从列表中获取当前项目。 You are just showing the last item entered. 您只显示最后输入的项目。 If I understand your problem correctly, this should work. 如果我正确理解您的问题,则应该可以。

using System;
using System.Collections.Generic;

namespace ListProgram
{
 class Program
 {
    static void Main(string[] args)
    {
        string varListInput = null;
        Boolean varIsValid = true;
        Int32 intTime = 3000000;

        while (varIsValid) //don't really understand why you need/have this while loop, but not the question
        {
            try
            {
                Console.Clear();
                Console.WriteLine("Welcome to OTC CIS120"); //you're already using WriteLine, you don't need to append \n
                Console.WriteLine("ACME Co. Item Locator List Program");
                Console.WriteLine(); //for one line spacing between header and user input

                var ItemList = new List<string>();

                for (int i = 0; i < 10; i++) // Continue For Loop until i is > List amount.
                {
                    Console.WriteLine($"{i + 1}: Enter Item Name To Add To Inventory");
                    varListInput = Console.ReadLine(); // User inputs value into field.
                    ItemList.Add(varListInput);
                }

                Console.WriteLine("Items Added To Inventory Are: ");
                //just personal perfence to do it this way rather than list.reverse()
                //item count is 10, but the highest index is only 9.
                for (int i = (ItemList.Count - 1); i >=0; i--)
                {
                    var item = ItemList[i];//need to get the current item from the list
                    Console.WriteLine($"{i +  1}: {item}");
                }

                System.Threading.Thread.Sleep(intTime);//please do NOT EVER use Thread.Sleep in production code
            }

            catch (Exception e)//since Console.ReadLine returns a string I'm not sure what errors this code would produce, therefore when it would stop.
            {
                Console.WriteLine("The Program Has an Error: " + e.Message);
                varIsValid = false;
                System.Threading.Thread.Sleep(intTime);
                Environment.Exit(0); //Exit the program
            }
        }
    }
  }
}

and produced this output 并产生了这个输出 在此处输入图片说明

Remember that every time the while loop starts over the item list is cleared and nothing will be retained between runs. 请记住,每次while循环从项目列表开始时都会被清除,并且两次运行之间不会保留任何内容。

Edit 1 If you do want to use .Reserve() you don't need the second for loop anymore. 编辑1如果确实要使用.Reserve(),则不再需要第二个for循环。 You could do something like this in between 您可以在两者之间做这样的事情

Console.WriteLine("Items Added To Inventory Are: "); Console.WriteLine(“添加到库存的项目为:”);

    ItemList.Reverse();
    ItemList.ForEach(i => Console.WriteLine(i));

and

Thread.Sleep(...) Thread.Sleep(...)

Edit 2 Using .Reverse() and a second loop (either .ForEach or for (...)) is going to be worse performing than my original single for loop that starts at the end, but you will only notice it on VERY large lists or in loops that do a lot of computations. 编辑2使用.Reverse()和第二个循环(.ForEach或for(...))的性能将比结尾处开始的原始原始for循环差,但您只会在非常大的时候注意到它列出或进行大量计算的循环。

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

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