当数组满时程序关闭,也需要搜索和排序



我正在尝试设置我的SortFind。能够按名称和价格排序,与find.

功能相同
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace sodacrate
{
    class Bottles           //skapar klassen Soda för att samla information om innehållet i backens SMAK, PRIS och av vilken TYP drickan är (vatten eller läsk) s.134->
    {
        string flavor;      //{ "Cola", "Water", "Orange", "Raspberry", "GrapeTonic" }
        int price;          // 4, 5, 6, 7, 8

        //METOD: CONSTRUCTOR
        public Bottles(string flavor, int price)
        {
            this.flavor = flavor;
            this.price = price;
        }
        //Egenskap för flavor
        public string Flavor
        {
            get { return flavor; }
            set { flavor = value; }
        }
        //Egenskap för price
        public int Price
        {
            get { return price; }
            set { price = value; }
        }
        public override string ToString()
        {
            return string.Format(Flavor + " " + Price);
            //return string.Format("The bottle {0} costs {2} G.", flavor, price);
        }
    }

    class Sodacrate
    {
        Bottles[] myCrate = new Bottles[25];            //create empty array that holds 25
        string[] flavors = new string[25];              //create empty list of current flavors in crate   
        int[] prices = new int[25];                     //create empty list of current prices in crate          
        //List<string> flavors = new List<string>();      //create empty list of current flavors in crate
        //List<int> prices = new List<int>();
        private int amountBottles = 0;                  //Identifierare. Håller reda på antal flaskor
        public int crateValue = 0;                      //Sammanlagda värdet på alla flaskor som finns i backen
        public void Run()
        {
            int temp = 0;
            do
            {
                Console.Clear();
                Console.WriteLine("nnnn");
                Console.WriteLine("*********************************************");
                Console.WriteLine("**       Welcome to your Sodacrate!        **");
                Console.WriteLine("*********************************************");
                Console.WriteLine("*                                           *");
                Console.WriteLine("*        These are your options:            *");
                Console.WriteLine("*                                           *");
                Console.WriteLine("*        1. Add soda to your crate          *");
                Console.WriteLine("*        2. Print the content               *");
                Console.WriteLine("*        3. Calculate the content           *");
                Console.WriteLine("*        4. Sort sodas                      *");
                Console.WriteLine("*        5. Find sodas                      *");
                Console.WriteLine("*        6. Remove bottles                  *");
                Console.WriteLine("*        0. Quit                            *");
                Console.WriteLine("*                                           *");
                Console.WriteLine("*                                           *");
                Console.WriteLine("*********************************************");
                Console.WriteLine("nnnn");
                temp = int.Parse(Console.ReadLine());
                switch (temp)
                {
                    case 1:
                        add_soda();
                        break;
                    case 2:
                        print_crate();
                        break;
                    case 3:
                        calc_total();
                        break;
                    case 4:
                        sort_sodas();
                        break;
                    case 5:
                        find_soda();
                        break;
                    case 6:
                        remove_soda();
                        break;
                    case 0:
                        Console.WriteLine("Shutting down program");                         //avsluta programmet.
                        break;
                    default:
                        Console.WriteLine("Incorrect Input");                              //skrivs ut om annat än en siffra mellan 0-6 anges.
                        break;
                }
            } while (temp != 0);
        }
        public void add_soda()
        {
            int adding = 0;
            do
            {
                //Console.Clear(); //tar bort all föregående text i konsolfönstret
                //menyn för att välja smak
                Console.WriteLine("nnn");
                Console.WriteLine("*****************************************************");
                Console.WriteLine("**           Which flavor do you like?             **");
                Console.WriteLine("*****************************************************");
                Console.WriteLine("*                                                   *");
                Console.WriteLine("* Choose by selecting 1-5 and ENTER or 0 to go back *");
                Console.WriteLine("*                                                   *");
                Console.WriteLine("*            1. COLA.         Costs 4 G             *");
                Console.WriteLine("*            2. WATER.        Costs 5 G             *");
                Console.WriteLine("*            3. ORANGE.       Costs 6 G             *");
                Console.WriteLine("*            4. RASPBERRY     Costs 7 G             *");
                Console.WriteLine("*            5. GRAPE TONIC   Costs 8 G             *");
                Console.WriteLine("*            0. Return to Main Menu                 *");
                Console.WriteLine("*                                                   *");
                Console.WriteLine("*****************************************************");
                Console.WriteLine("nnnn");
                adding = int.Parse(Console.ReadLine());
                //själva valen, input 0-5 och sen ENTER för att verkställa
                if (amountBottles >= 25)
                {
                    Console.WriteLine(" - Your crate is full!");
                    Console.WriteLine(amountBottles);
                }
                else
                {
                    switch (adding)
                    {
                        case 1:
                            Bottles Cola = new Bottles("Cola", 4);
                            myCrate[amountBottles] = Cola;
                            Console.WriteLine("Cola");
                            break;
                        case 2:
                            Bottles Water = new Bottles("Water", 5);
                            myCrate[amountBottles] = Water;
                            Console.WriteLine("Water");
                            break;
                        case 3:
                            Bottles Orange = new Bottles("Orange", 6);
                            myCrate[amountBottles] = Orange;
                            Console.WriteLine("Orange");
                            break;
                        case 4:
                            Bottles Raspberry = new Bottles("Raspberry", 7);
                            myCrate[amountBottles] = Raspberry;
                            Console.WriteLine("Raspberry");
                            break;
                        case 5:
                            Bottles GrapeTonic = new Bottles("GrapeTonic", 8);
                            myCrate[amountBottles] = GrapeTonic;
                            Console.WriteLine("Grape Tonic");
                            break;
                        default:
                            Console.WriteLine("Incorrect Input");
                            break;
                    }
                    amountBottles++;
                }
            }while (adding != 0);
        }

        public void print_crate()
        {
            int keepshopping1 = 0;
            do
            {
                amountBottles--;        //removes the extra unidentified bottle that always ends up in the crate when calling upon add_soda
                Console.Clear();
                Console.WriteLine("*******************************************************");
                Console.WriteLine("**           Contents of your Soda Crate             **");
                Console.WriteLine("*******************************************************");
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Purchase more bottles?n" + "[1] to Purchase, [2] to Remove bottles or [0] to go back to Main Menu. ");
                Console.WriteLine("nn");
                Console.WriteLine("Amount of bottles in your crate: " + amountBottles );
                int i = 0; //counting variable
                while (myCrate[i] != null) //counts while no element in myCrate is null
                {
                    string temp = myCrate[i].Flavor; // gets the "name" property of the object
                    flavors[i] = temp;
                    //flavors.Add(temp); //adds the name property to the list "flavors" -LIST-funktionen
                    i++;
                }
                var a = from x in flavors //orders and counts duplicates in list
                        group x by x into g
                        let count = g.Count()
                        orderby count descending
                        select new { Value = g.Key, Count = count };
                foreach (var x in a)

                    Console.WriteLine(x.Value + " " + x.Count + " bottles");       //prints sorted, grouped list
                keepshopping1 = int.Parse(Console.ReadLine());
                switch (keepshopping1)
                {
                    case 1:
                        add_soda();
                        break;
                    case 2:
                        remove_soda();
                        break;
                    case 0:                                                                //tillbaka till huvudmenyn
                        break;
                    default:
                        Console.WriteLine("Incorrect Input");                              //skrivs ut om annat än en siffra 1,2 eller 0 anges.
                        break;
                }
            } while (keepshopping1 != 0);
        }
        public void calc_total()
        {
            int sum = 0;
            int keepshopping2 = 0;
            do
            {
                Console.Clear();
                Console.WriteLine("*******************************************************");
                Console.WriteLine("**             Cost of your Soda Crate               **");
                Console.WriteLine("*******************************************************");
                Console.WriteLine();
                int i = 0; //counting variable
                crateValue = sum;
                while (myCrate[i] != null) //counts while no element in myCrate is null

                {
                    sum = sum + myCrate[i].Price;
                    i++;
                }
                    Console.WriteLine("This will be " + sum + " G's, sir.");
                    Console.WriteLine("nn");
                    Console.WriteLine("Continue shopping?n" + "[1] to Continue, [2] to Remove soda or [0] to go back to Main Menu. ");
                    Console.WriteLine("nn");

                keepshopping2 = int.Parse(Console.ReadLine());
                switch (keepshopping2)
                {
                    case 1:
                        add_soda();
                        break;
                    case 2:
                        remove_soda();
                        break;
                    case 0:                                                                //tillbaka till huvudmenyn
                        break;
                    default:
                        Console.WriteLine("Incorrect Input");                              //skrivs ut om annat än siffra 1,2 eller 0 anges.
                        break;
                }
            } while (keepshopping2 != 0);       
            //Tänk på att inte räkna med tomma positioner i vektorn
        }
        public void find_soda()
        {
        }
        public void sort_sodas()
    {
        int max = myCrate.Length - 1;
        //outer loop: Goes through the entire list until everything's sorted
        for (int m = 0; m < max; m++)
        {
            //inner loop: Goes through every element and comparing them to eachother. Doesn't go through what's already sorted.
            int sorted = max - m;   //to see how many has been gone through
            for (int n = 0; n < sorted; n++)
            {
                if (myCrate[n] > myCrate[n+1])  //comparing elements ERROR cs0019
                {
                    //switch place
                    int temp3 = myCrate[n];
                    myCrate[n] = myCrate[n+1];
                    myCrate[n+1] = temp3;
                }
            }
        }
        //write the list
        for (int m = 0; m < myCrate.Length; m++)
            Console.WriteLine(myCrate[m]);
    }
    public void remove_soda()
    {
        if (myCrate == null)
        {
            Console.WriteLine("Your crate is empty. ");
            Console.ReadKey();
            return;
        }
        Console.WriteLine("Name on the bottle: ");
        string name = Console.ReadLine();
        if (myCrate.Select(x => x.Flavor).Contains(flavors))   //errorcs1929
        {
            var itemToRemove = myCrate.Where(x => x.Flavor.Equals(flavors)).First();
            if (itemToRemove != null)
                myCrate.Remove(itemToRemove);   //error 1061 - 'Bottles[]' cannot contain a definition for 'Remove'
        }
        else
        {
            Console.WriteLine("Name not found. ");
            Console.ReadKey();
        }
    }

    }
    class Program
    {
        public static void Main(string[] args)
        {
            //Skapar ett objekt av klassen Sodacrate som heter Sodacrate
            var Sodacrate = new Sodacrate();
            Sodacrate.Run();
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

编辑

我已经尝试过这个方法remove_soda,但我不能得到我的头周围我错了

if (myCrate == null)
            {
                Console.WriteLine("Your crate is empty. ");
                Console.ReadKey();
                return;
            }
            Console.WriteLine("Name on the bottle: ");
            string name = Console.ReadLine();
            if (myCrate.Select(x => x.Flavor).Contains(flavors))
            {
                var itemToRemove = myCrate.Where(x => x.Flavor.Equals(flavors)).First();
                if (itemToRemove != null)
                    myCrate.Remove(itemToRemove);
            }
            else
            {
                Console.WriteLine("Name not found. ");
                Console.ReadKey();
            }

这是我在sort_soda

中完成的气泡排序
public void sort_sodas()
{
    int max = myCrate.Length - 1;
    //outer loop: Goes through the entire list until everything's sorted
    for (int m = 0; m < max; m++)
    {
        //inner loop: Goes through every element and comparing them to eachother. Doesn't go through what's already sorted.
        int sorted = max - m;   //to see how many has been gone through
        for (int n = 0; n < sorted; n++)
        {
            if (myCrate[n] > myCrate[n+1])  //comparing elements
            {
                //switch place
                int temp3 = myCrate[n];
                myCrate[n] = myCrate[n+1];
                myCrate[n+1] = temp3;
            }
        }
    }
    //write the list
    for (int m = 0; m < myCrate.Length; m++)
        Console.WriteLine(myCrate[m]);
}

然而,它给了我3个错误。

1:操作符'>'不能用于'Bottles'和'Bottles'类型的操作数

2:不能隐式转换类型'sodacrate '。

3:不能隐式地将类型'int'转换为'sodacrate '。瓶"

for (int i = 0; i < 25; i++)的读取为当i从0开始时,当i小于25时,每次循环将i增加1

所以如果我<25 .它永远不会== 25

数组是为固定不变的数据而设计的,我建议使用List

List<Bottles> Crate = new List<bottles>();

那么你可以做

if (Crate.Count >= 25)
{
    Console.WriteLine(" - Your crate is full!");
}
else
{
    Crate.Add(bottle);
}

break表示立即退出循环并停止执行,因此当i=0时按break, for循环停止工作

continue表示立即退出循环,然后从开始

继续执行

来分组你的结果那么Linq是你的朋友

crate.Groupby(b=>b.Flavor).Select(g=>g.Count() + " " + g.Key);

将返回一个可枚举的字符串

同样,你可以使用Linq的Orderby()对 进行排序。
crate.Orderby(b=>b.Price)

也可以使用Linq的Where()来搜索

crate.Where(b=>b.Flavour == SearchField)

编辑:更明确一点,你的Add函数应该像这样

adding = int.Parse(Console.ReadLine());
if (amountBottles >= 25)
{
    Console.WriteLine(" - Your crate is full!");
}
else
{
    //Your Switch statement here
    amountBottles++;
}

和你的打印应该是

for (int i = 0; i < myCrate.Length; i++)
{
    if (myCrate[i] != null)
    {
        Console.WriteLine( myCrate[i].Flavor  );
    }
    else
    {
        Console.WriteLine("Empty Space");
    }
}

编辑:当你想用LINQ进行分组和排序时然后,对于分组,您需要创建一个group类,该类将保存您的瓶子类型和计数,同时生成总数,然后使用该组进行打印

的排序那么你会想要实现一个排序算法,最好的是快速排序虽然插入排序更简单

相关内容

  • 没有找到相关文章