0

当我打印我的列表(库存)时,它会多次打印相同的值,而不是正确迭代:

List<Coffee> inventory = new List<Coffee>();

        Console.Write("Enter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast ");
        string s = Console.ReadLine();
        string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        // Loop
        while (!s.ToLower().Equals("q"))
        {
            string name = values[0];
            string demand = (values[1]);
            string cost = (values[2]);
            string min = values[3];


            float D = CheckDemand(demand);
            float C = CheckCost(cost);
            float M = CheckMin(min);

            Decaf decafCoffee = new Decaf(name, D, C, M);
                   inventory.Add(decafCoffee);

            Console.Write("\nEnter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast: ");
            s = Console.ReadLine();
        }   // End loop

        // Display values
        Console.WriteLine("\nName \t   C ($)      Demand \t  Detail   Q(lbs.)     TAC ($)      T(weeks) ");
        for (int j = 0; j < inventory.Count; j++)
        {
            Console.WriteLine("{0}", inventory[j].toString());
        }

任何想法为什么会这样?我需要实现某个接口吗?

4

3 回答 3

2

string[]使用while 循环内的值移动行:

 string s = Console.ReadLine();
 // Loop
 while (!s.ToLower().Equals("q"))
 {
      string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
      ...
于 2013-04-25T17:13:37.070 回答
1

当你调用ToString()一个对象时,你通常只会得到类型的完全限定名。这取决于您希望看到打印的内容,但您应该尝试显示 Coffee 类的成员。例如:

foreach(Coffee c in inventory)
{
   Console.WriteLine(c.Name);
}

我继续将您从for循环切换到foreach.

于 2013-04-25T17:11:23.530 回答
0

你需要把

string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

在你的 while 循环内。

于 2013-04-25T17:14:05.827 回答