C# C-不向第一个空数组的索引中添加元素

C# C-不向第一个空数组的索引中添加元素,c#,arrays,null,element,add,C#,Arrays,Null,Element,Add,嗨,我目前正在做一个学校项目,我们必须在碳酸饮料中加入苏打水。我是编程新手,你们知道的。我遇到了一个无法解决的问题。例如,当我在数组索引0、1和2处添加3份苏打水,然后删除索引1处的元素时。如果我继续添加苏打水,它不会在索引1中添加苏打水,而是继续索引3。 对不起,我不知道还有什么办法可以解释这个问题。 如果您注意到任何其他问题,如果您能指出,我将非常感激 提前谢谢 class Soda { private string name; private int price;

嗨,我目前正在做一个学校项目,我们必须在碳酸饮料中加入苏打水。我是编程新手,你们知道的。我遇到了一个无法解决的问题。例如,当我在数组索引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);
    }
}

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

你的评论似乎是瑞典语,但实际上没有帮助。 但是,您可能想做的是删除将值设置为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;


    }

请发布尽可能少的代码。阅读如何创建一个