【问题标题】:Having trouble with adding a update () method to my console inventory application在我的控制台清单应用程序中添加 update () 方法时遇到问题
【发布时间】:2018-12-05 23:27:21
【问题描述】:

我正在制作一个简单的库存控制台应用程序。
到目前为止,我有以下代码:

using System;
using System.Collections;

class Inventory
{
    string name;
    double cost;
    int onhand;

    public Inventory(string n, double c, int h)
    {
        name = n;
        cost = c;
        onhand = h;
    }

    public override string ToString()
    {
        return
          String.Format("{0,-10}Cost: {1,6:C}  On hand: {2}", name, cost, onhand);
    }
}

public class InventoryList
{
    public static void Main()
    {
        ArrayList inv = new ArrayList();

        // Add elements to the list 
        inv.Add(new Inventory("Pliers", 5.95, 3));
        inv.Add(new Inventory("Wrenches", 8.29, 2));
        inv.Add(new Inventory("Hammers", 3.50, 4));
        inv.Add(new Inventory("Drills", 19.88, 8));

        Console.WriteLine("Inventory list:");
        foreach (Inventory i in inv)
        {
            Console.WriteLine("   " + i);
        }

我添加了此代码以将新产品添加到列表中。

        Console.WriteLine("\n");
        Console.WriteLine("Input New Inventory");
        Console.WriteLine("Name : ");
        string newName = Console.ReadLine();
        Console.Write("Cost : ");
        double newCost = Double.Parse(Console.ReadLine());
        Console.Write("Onhand : ");
        int newOnhand = Int32.Parse(Console.ReadLine());

        inv.Add(new Inventory(newName, newCost, newOnhand));

        Console.WriteLine("\n");
        Console.WriteLine("Inventory List:");
        foreach (Inventory i in inv)
        {
            Console.WriteLine("" + i);
        }
        Console.WriteLine("\n")
    }
}

我无法弄清楚如何添加 update() 方法来更改列表中的库存编号。

我的问题是如何在控制台窗口中添加更新方法来更改列表中的库存数量?
在控制台中,我将输入产品名称和新库存编号,然后返回一个包含产品更新库存编号的新列表。

【问题讨论】:

  • 你必须使用ArrayList吗?您必须使用 LINQ 查询它(请参阅 herehere),但对于您当前的知识水平,LINQ 可能太先进了。也许字典是一个更简单的选择,产品名称作为键,Inventory 对象作为值。

标签: c# console inventory


【解决方案1】:

我同意 Stijn 的评论。 Dictionary 或 List 将是比 ArrayList 更好的解决方案 - 但如果您必须使用 ArrayList - 您可以编写一个函数来返回索引并使用它来更新您的 ArrayList:

    private static int GetIndex(string name, ArrayList inv)
    {
        for (var i = 0; i < inv.Count; i++) 
        {
            if (((Inventory)inv[i]).Name.Equals(name))
            {
                return i;
            }
        }

        return -1; 
    }

然后在main中:

        var index = GetIndex("Drills", inv);
        if (index >= 0)
        {
            ((Inventory)inv[index]).StockNumber = 15; // Or whatever...
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多