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

时间:2018-10-21 20:05:31

标签: c# string list console-application user-input

如何将用户输入存储到“列表” List<string> ItemList中,然后输出输入的内容?

当前,当我运行程序时,用户可以在varItemInput中输入值,并且for循环继续进行,直到输入了10个条目为止,但是随后不输出输入的值,而是输出10个空列表值。我在做什么错了?

我认为错误是,它没有将用户输入存储到varItemInput中,而只是输出了预定义的空List.Add("");值。

我如何使用户填充的列表最多10个条目?

这应该像一个“库存程序”,在该程序中,用户输入了诸如Hammer之类的项目,然后在输入10次之后,将在输出屏幕上显示所有10个条目。

我知道如何使用数组来执行此操作,但是此特定程序必须使用列表来完成。

这是我的代码

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
            }
        }
    }
}

}

2 个答案:

答案 0 :(得分:2)

您无需为此保留列表项,例如,如果您只需要添加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);
}

但是,要替换列表项的值,您只需分配新值即可,例如:

ItemList[i] = newStringValue;

答案 1 :(得分:0)

在您的原始帖子中,您没有从列表中获取当前项目。您只显示最后输入的项目。如果我正确理解了您的问题,则应该可以。

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
            }
        }
    }
  }
}

并产生此输出 enter image description here

请记住,每次while循环从项目列表开始时都会被清除,并且两次运行之间不会保留任何内容。

编辑1 如果您确实想使用.Reserve(),则不再需要第二个for循环。您可以在两者之间做类似的事情

  

Console.WriteLine(“添加到库存的项目为:”);

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

  

Thread.Sleep(...)

编辑2 使用.Reverse()和第二个循环(.ForEach或for(...))的性能将比结尾处开始的原始原始for循环差,但您只会在非常大的列表中注意到它,或者在进行大量计算的循环中。