首页 > 解决方案 > C# - 不向第一个空数组的索引添加元素

问题描述

嗨,我目前正在开展一个学校项目,我们必须将苏打水添加到 sodacrate 中。我是编程新手,所以你们知道。我遇到了一个我无法解决的问题。例如,当我在数组索引 0,1 和 2 处添加 3 个苏打水,然后在索引 1 处删除元素时。如果我然后返回添加苏打水,它不会将苏打水添加到索引 1 并继续索引 3 . 抱歉,我不知道有什么其他方法可以解释这个问题。如果您发现任何其他问题,如果您能指出它们,我将非常感激!

提前致谢!

class Soda
{
    private string name;
    private int price;
    private string type;

    public Soda(string _name, int _price, string _type)
    {
        name = _name;
        price = _price;
        type = _type;
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }    

    public int Price
    {
        get { return price; }
        set { price = value; }
    }

    public string Type
    {
        get { return type; }
        set { type = value; }
    }

}

class Sodacrate
{
    private Soda[] sodas = new Soda[25];
    private Soda[] content = new Soda[10];
    private int amount_bottles = 0;

    public void Run()
    {
        Console.Clear();

        int alternatives;
        do
        {
            Console.WriteLine("-=Sodacrate-Simulator=-");
            Console.WriteLine("\n===========");
            Console.WriteLine("HUVUDMENY");
            Console.WriteLine("===========\n");
            Console.WriteLine("Välj alternativ");
            Console.WriteLine("------------------");
            Console.WriteLine("[1] Lägg till dryck i Läskbacken");
            Console.WriteLine("[2] Skriv ut innehållet i läskbacken");
            Console.WriteLine("[3] Beräkna det totala värdet av läskbacken");
            Console.WriteLine("[4] Sök efter dryck");
            Console.WriteLine("[5] Avsluta programmet\n");
            while (true)
            {
                try
                {
                    alternatives = int.Parse(Console.ReadLine());
                    break;
                }
                catch (Exception)
                {
                    Console.WriteLine("Ogiltigt val");
                }
            }

            switch (alternatives)
            {
                case 1: add_soda();
                    break;
                case 2: print_crate();
                    break;
                case 3: calc_total();
                    break;
                case 4: find_soda();
                    break;
                case 5: Console.WriteLine("Programmet avslutas...");
                    break;
                default: Console.WriteLine("Felaktig inmatning"); Console.Clear();
                    break;
            }

        } while (alternatives != 5);

    }

    public void add_soda()
    {
        if (amount_bottles == 25)
        {
            Console.WriteLine("\nLäskbacken är full!");
            Console.WriteLine("Tryck på valfri tangent för att gå tillbaka!");
            Console.ReadKey();
            Run();
        }

        Console.Clear();
        //list of different sodas
        content[0] = new Soda("Coca-Cola", 13, "Läsk");
        content[1] = new Soda("Sprite", 10, "Läsk");
        content[2] = new Soda("Fanta", 12, "Läsk");
        content[3] = new Soda("Redbull", 25, "Energidryck");
        content[4] = new Soda("Powerking", 20, "Energidryck");
        content[5] = new Soda("Loka", 14, "Kolsyrat Vatten");
        content[6] = new Soda("Ramlösa", 15, "Kolsyrat Vatten");
        content[7] = new Soda("Spendrups", 15, "Öl");
        content[8] = new Soda("Carlsberg", 17, "Öl");
        content[9] = new Soda("Heineken", 16, "Öl");

        int choice;
        int index = 1;

        Console.WriteLine("\n-=Välj dryck=-     Antal flaskor: [{0}/25]\n", amount_bottles);
        Console.WriteLine("{0,1} {1,10} {2,13} {3,10}", "Index:", "Namn:", "Pris:", "Sort:");
        Console.WriteLine("-----------------------------------------------------");
        foreach (var soda in content)
        {
            Console.WriteLine("{3,-10} {0,-15} {1,-9} {2}", soda.Name, soda.Price, soda.Type, index++);
        }

        Console.WriteLine("-----------------------------------------------------");
        Console.WriteLine("\nVälj ett index för att lägga till dryck eller [0] för att avbryta.");

         for (int i = 0; i < sodas.Length; i++)
         {

            choice = int.Parse(Console.ReadLine());

            if (choice < 0 || choice > 10)
            {
                i--;
                Console.WriteLine("Skriv endast in ett index mellan 1-10 eller 0 för att avbryta!");
            }
            else if (choice == 0)
            {
                break;
            }
            else if (i == sodas.Length ) // om läskbacken är full går den tillbaka till Huvudmenyn.
            {
                Run();
            }
            else if (sodas[i] == null)
            {
                sodas[i] = content[choice - 1];
                amount_bottles++;
                Console.WriteLine("Du har lagt till {0}. [{1}/25]", content[choice - 1].Name, amount_bottles);
            }
            else
            {
                Console.WriteLine("Ogiltig inmatning!");
            }
         }


        Console.Clear();

    }

    public void print_crate()
    {
        Console.Clear();

        int index = 1;
        Console.WriteLine("-=Läskbackens innehåll=-      Antal flaskor: [{0}/25]\n ", amount_bottles);
        Console.WriteLine("{0,1} {1,10} {2,13} {3,10}", "Index:", "Namn:", "Pris:", "Sort:");
        Console.WriteLine("-----------------------------------------------------");
        foreach (var soda in sodas)
        {
            if (soda != null)
            {
                Console.WriteLine("{3,-10} {0,-15} {1,-9} {2}", soda.Name, soda.Price, soda.Type, index++);
            }

            else
            {
                Console.WriteLine("{3,-10} {0,-15} {1,-10} {2}", "Tom Plats", "-" , "-" ,index++);
            }
        }

        Console.WriteLine("-----------------------------------------------------");
        Console.WriteLine("Tryck på valfri tangent för att gå tillbaka till Huvudmenyn...");
        Console.ReadKey();
        Console.Clear();
    }

    public int calc_total()
    {
        Console.Clear();
        int sum = 0;
        foreach (var soda in sodas)
        {
            if (soda != null)
            {
                sum += soda.Price;
            }
        }
        Console.WriteLine("Den totala värdet av läskbacken är {0} kronor.\n", sum);
        Console.WriteLine("Tryck på valfri tangent för att gå till Huvudmenyn...");
        Console.ReadKey();
        Console.Clear();
        return sum;
    }

    public void find_soda()
    {
        Console.Clear();

        Console.WriteLine("\n -=Sök efter dryck=-\n");
        Console.WriteLine("Skriv in dryckens namn:");
        string name = Console.ReadLine();

        for (int i = 0; i < sodas.Length; i++)
        {
            if (sodas[i].Name == name)
            {
                Console.WriteLine("Drycken: {0} finns på indexet:{1}\n", sodas[i].Name, i+1);

                Console.WriteLine("[T]Vill du ta bort drycken?");
                Console.WriteLine("[G]å tillbaka till Huvudmenyn");
                string inmatat = Console.ReadLine();
                if (inmatat == "t" || inmatat == "T")
                {
                    amount_bottles--;
                    sodas[i] = null;
                    break;
                }
                else if (inmatat == "g" || inmatat == "G")
                {
                    break;
                }
            }
            else if (sodas[i].Name != name)
            {
                Console.WriteLine("Drycken hittades inte på indexet: {0}.", i+1);
            }
            else
            {
                Console.WriteLine("Drycken hittades inte.");
                break;
            }
        }
        Console.WriteLine("Tryck på valfri tangent för att gå till Huvudmenyn...");
        Console.ReadKey();
        Console.Clear();
    }

}

class Program
{
    static void Main(string[] args)
    {
        Console.Clear();
        Console.BackgroundColor = ConsoleColor.White;
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.SetWindowSize(90, 39);
        var sodacrate = new Sodacrate();
        sodacrate.Run();
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

标签: c#arraysnullelementadd

解决方案


没错,数组是固定的,你不能动态增加它的大小。但是,您可以创建一个更大尺寸的新数组,复制以前的值并将新项目设置为等于新值。

您的评论似乎是瑞典语,这并没有真正的帮助。但是,您可能想要做的而不是删除将值设置为 null,并在添加时检查元素是否为 null 并将其设置为新值。如果没有一个数组是空的,则将数组复制到具有原始大小+1的新数组

        int originalSize = 10;
        object[] sodas = new object[originalSize];

        void RemoveSodaAtIndex(int index)
        {
            if(index >= 0 && index < sodas.Length)
            {
                sodas[index] = null;
            }
        }

        void AddSoda(object s)
    {
        for(int i = 0; i < sodas.Length;i++)
        {
            if(sodas[i]==null)
            {
                sodas[i] = s;
                return;
            }
        }

        originalSize += 1;
        object[] temp = new object[originalSize];
        for (int i = 0; i < temp.Length; i++)
        {
            if (i != temp.Length - 2)
            {
                temp[i] = sodas[i];
            }
            else
            {
                temp[i] = s;
            }
        }
        sodas = temp;


    }

推荐阅读