-1

I'm trying to set up my Sort and Find. To be able to Sort by name and price, and same functions with 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("\n\n\n\n");
                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("\n\n\n\n");
                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("\n\n\n");
                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("\n\n\n\n");

                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("\n\n");
                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("\n\n");
                    Console.WriteLine("Continue shopping?\n" + "[1] to Continue, [2] to Remove soda or [0] to go back to Main Menu. ");
                    Console.WriteLine("\n\n");


                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);
        }
    }
}

EDIT

I've tried this in method remove_soda, but I can't get my head around where I go wrong

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();
            }

And here's my noble try to accomplish a bubble sort in sort_sodas

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]);

}

However, it gives me 3 Errors.

1: Operator '>' cannot be applied to operands of type 'Bottles' and 'Bottles'.

2: Cannot implicitly convert type 'sodacrate.Bottles' to 'int'

3: Cannot implicitly convert type 'int' to 'sodacrate.Bottles'

Servy
  • 202,030
  • 26
  • 332
  • 449
thatkoffE
  • 1
  • 3
  • Your code has quite a few problems here; I'm not sure if a single answer could really make the code functional, but I'll try to offer a few observations that might help you. – Claies Sep 01 '16 at 10:48
  • First, you are trying to see if `amountBottles == 25`, which is good, but when you add a new bottle, you are doing `i++` rather than `amountBottles++`, which means `amountBottles` will always be `0`. – Claies Sep 01 '16 at 10:48
  • Secondly, a `for` statement doesn't even really make sense the way you wrote it; you are essentially looping through 25 times, and each time, checking to see if `amountBottles == 25`, but not only is `amountBottles` never going to change inside the loop, the only thing that you are accomplishing here is printing `" - Your crate is full!"` 25 times in a row. – Claies Sep 01 '16 at 10:51
  • Also, since you are using `i++` outside the loop, but then defining the loop as `for (int i = 0 ......)` you are resetting `i` when the loop runs, causing the prior statements to be useless (though they were already flawed, see prior comments). – Claies Sep 01 '16 at 10:52
  • because you are doing `amountBottles++` in the loop rather than when the bottle is added, the first bottle added is going to run the loop, set `amountBottles` to 25 before the loop is done, and `amountBottles` has no attachment to the number of bottles, only the number of times the loop has changed it. – Claies Sep 01 '16 at 10:56
  • the NullRef is because something in your array is empty, so add a `if(myCrate[i] != null)` – MikeT Sep 01 '16 at 16:07

1 Answers1

2

for (int i = 0; i < 25; i++) reads as when i starts at 0 and while i is less than 25 then increment i by 1 each loop

so if i < 25 it will never == 25

arrays are designed for fixed unchanging data i would instead suggest using List

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

then you can do

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

break means immediately exit loop and stop executing so when you hit break on i=0 the for loop stops working

continue means immediately exit loop and then continue executing from beginning

for grouping your results then Linq is your friend

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

will return an enumerable of strings

like wise you can use Linq's Orderby() to sort

crate.Orderby(b=>b.Price)

Also you can use Linq's Where() to search

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

EDIT: to be a little more explicit your add function should look like this

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

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

and your print should be

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

    else
    {
        Console.WriteLine("Empty Space");
    }
}

EDIT: As you want to do the grouping and sorting with out LINQ then for the grouping you will need to create a group class that will hold your bottle type and count while you make the total s then use the group for the printing

for the sorting then you will want to implement a sort algorithm, the best would be Quick Sort though Insertion Sort is simpler

MikeT
  • 5,398
  • 3
  • 27
  • 43
  • 1
    then in the interest of simplicity your teacher is teaching you the wrong method, in which case you can use Linq again `crate.Count(b=>b!=null)` just remember to set the arrayitem to null after the bottle is removed – MikeT Sep 01 '16 at 11:03
  • this course just went from 0 to 100 so I'm afraid I don't understand what you're saying. If I want the Groupby and Orderby methods to work, I have to set them in my constructor Bottles in the class Bottles? – thatkoffE Sep 01 '16 at 11:22
  • null is the c# way of saying nothing, so crate.Count(b=>b!=null) reads as count all the values in Crate that are set to nothing, so when you remove a bottle you need to do crate[ <> ] = null – MikeT Sep 01 '16 at 11:38
  • you also need to think about the process you are doing, so if you were going to add something to a create think what you would do step by step, then you will realise things like you have to check if the crate is full before adding not after – MikeT Sep 01 '16 at 11:59
  • @MikeT this is part of the problem with people asking homework questions here. We want to be helpful and show them the most effective solution, but that is actually less helpful, because their teacher is expecting them to use specific constructs to understand specific concepts. It's similar to the "you have to know how to walk before you can run" idea. – Claies Sep 01 '16 at 12:15
  • @Claies true you have to walk before you can run, but its not best to stop them from running by tying their ankles together. which is why i pointed out that the teacher was teaching the wrong method because its a simpler structure. my personal choice would be to teach with the more advanced structures that take some of the complexity out, then once they can walk with some hand holding show them how the advanced structures work – MikeT Sep 01 '16 at 12:28
  • I appreciate you all trying to help me out @Claies and @MikeT! I've edited the post with some more info – thatkoffE Sep 01 '16 at 15:42
  • i've changed what happens when choosing a case in add_soda, but I can't seem to utilize the get- and sets from my properties – thatkoffE Sep 01 '16 at 15:51
  • Added a more explicit explanation about why your add isn't working – MikeT Sep 01 '16 at 16:01
  • @thatkoffE the problem is the object your are calling the get and set on is null – MikeT Sep 01 '16 at 16:19
  • @MikeT With that implemented, I get: CS1729 'Bottles' does not contain a constructor that takes 0 arguments – thatkoffE Sep 01 '16 at 16:25
  • @thatkoffE you missed the comment didn't you – MikeT Sep 01 '16 at 16:26
  • Clarified what i meant – MikeT Sep 01 '16 at 16:27
  • @MikeT I've now added if (myCrate[i] != null) in print_crate. Although, now for every soda I add in my crate, it adds three(!). Darn – thatkoffE Sep 01 '16 at 16:49
  • try removing the I property ie the `public int i { get; private set; }` you don't need it and its conflicting with every loop where you also use i – MikeT Sep 01 '16 at 16:53
  • that gives me 10 errors, for every line 'i' is written. "The name 'i' doesn not exist in the current context" – thatkoffE Sep 01 '16 at 16:57
  • hold on why are you donig `amountBottles++;` inside the if instead of printing the flavour? – MikeT Sep 01 '16 at 16:57
  • most of those errors are because you are using i to duplicate `amountBottles` – MikeT Sep 01 '16 at 16:58
  • also your calling to `amountBottles++` in your switch and then after it as well that means your code thinks each bottle is added twice – MikeT Sep 01 '16 at 17:03
  • Yeah, I removed amountBottles++ from my switch, at least now it only adds 1 unidentified bottle to my crate every time I go into the add_soda-menu. How do I print the flavour? I thought that was what I was doing with Console.WriteLine(myCrate[i].Flavor); EDIT saw your code now. Mine looks just like that – thatkoffE Sep 01 '16 at 17:05
  • see the edit for what i meant, the `amountBottles++` should only appear once when you add a bottle, just like `amountBottles--` should only because once when you successfully remove a bottle – MikeT Sep 01 '16 at 17:08
  • thank you, Mike! How should I get pass the problem with all my i:s? – thatkoffE Sep 01 '16 at 17:09
  • delete the 5 `i++` and replace the 5 `myCrate[i]`in the ***SWITCH*** statement only with 'myCrate[amountBottles]' – MikeT Sep 01 '16 at 17:12
  • THANK YOU!! I still can´t find how to NOT add the unidentified bottle, which adds itself every time I enter the add_soda-menu. – thatkoffE Sep 01 '16 at 17:19
  • update your code in the question and i'll have a look but my suspicion is that you are still calling `++` on amountBottles too many times – MikeT Sep 02 '16 at 08:12
  • @MikeT i've reworked the code a bit. Still there's a flaw, that adds an unidentified bottle whenever I enter add_soda. However, I set amountbottles-- when I enter print_crate to remove it. I know, it's bad. But for now, it's working as intended. – thatkoffE Sep 02 '16 at 09:37
  • the only source for your none existant bottle i can see if your `default:Console.WriteLine("Incorrect Input");` on the add, this is still increasing the bottle count even though no bottle was added, good attempt with the Linq query you've over complicated it but it should work, i've directed you to links for the sort algorithms – MikeT Sep 02 '16 at 09:59
  • my LINQ in print_crate is sorting the bottles by the amount of which flavor I have. Can't that be used in the sort? The sorting algorithms you linked to seems really hard! :) – thatkoffE Sep 02 '16 at 10:51
  • you can use the orderby command but that will create a new list of items that have been sorted you will then have to replace the values in your original array with the sorted ones – MikeT Sep 02 '16 at 12:52
  • I feel like this is way over my head, @MikeT, as nothing that I'm trying out is not working even the slightest. – thatkoffE Sep 02 '16 at 14:39
  • I think you are letting your self get put off by the Novelty of the situation, the first part of programming is Conceptualising you need to imagine your self performing the task and then you need to break down the task into groups of smaller task , then check each of those to see if they can be broken down eg to sort think how you would do it, you take 2 items compare them then place the smaller on the left and larger on the right, then move on to the next item, then you look at the Compare task how do you compare them, by price by flavour, etc once you have broken everything down its easy – MikeT Sep 02 '16 at 15:28
  • I've edited a bit, hopefully my teacher will see my efforts and not the ability to compile :P Thanks for all the help @MikeT, MUCH appreciated. At least you brough me more closer to a C instead of just an E, thank you! But I don't think I'm gonna sort out the find- and sort methods. studied 15 hours a day the entire week and due is sunday. – thatkoffE Sep 02 '16 at 16:32