【问题标题】:How to store user input into a List then output results - C# console program如何将用户输入存储到列表中然后输出结果 - C# 控制台程序
【发布时间】:2018-10-21 20:05:30
【问题描述】:

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

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

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

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

这应该类似于“库存程序”,其中用户输入像锤子这样的项目,然后在输入 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
            }
        }
    }
}

}

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢,但我试过你的答案,它只是挂断,不输出任何东西,或者只是保存最后输入的值。
    【解决方案2】:

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

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

    并产生了这个输出

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

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

    Console.WriteLine("添加到库存的项目是:");

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

    Thread.Sleep(...)

    编辑 2 使用 .Reverse() 和第二个循环(.ForEach 或 for (...))的性能将比我最初从末尾开始的单个 for 循环更差,但您只会在非常大的列表或在进行大量计算的循环中。

    【讨论】:

      猜你喜欢
      • 2019-07-07
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多