C# Programmet stänger ner sig när vektorn är full. Behöver en Sort och Find också. Väldigt Grön på detta

Permalänk
Medlem

C# Programmet stänger ner sig när vektorn är full. Behöver en Sort och Find också. Väldigt Grön på detta

Jag har nyss gjort om min kod och implementerat en klass för Bottles, med en konstruktor och egenskaperna smaker och pris.
Jag vill kunna skriva ut egenskaperna snyggt, ordnat och fint senare i metoden print_crate. Istället för endast input, som nu. Ex. har man valt 2 st Cola i metoden add_crate, så skrivs endast ut
Cola 4
Cola 4
ut nu utan att spara varken Cola(smaken) eller 4(priset).
Any whoooo.. När läskbacken är fylld i metoden add_soda med 25 st, och man lägger till en till,så skrivs ett felmeddelande ut på senast valda läsken: IndexOutOfRangeException was unhandled. Additional Information: Indes was outside the bounds of the array.

/* Just recently I've redone my code and implemented "myCrate" as an array and also wrote the class Bottles with a constructor.
Any how, after the implementation - my program shuts down and gives me an error, on the line which holds the most recently added item, whenever the array has been filled with more than 25 items. What I need it to do, and did before those implementations, is to write " - Your crate is full!". I've heard that this may be sorted out with get-set, but I have no clue how and haven't seen a good example anywhere. */

//Check if there is space in the crate. If there's 25, write: "Your crate is full!". for (int i = 0; i < 25; i++) { if (amountBottles == 25) { Console.WriteLine(" - Your crate is full!"); continue; } else { amountBottles++; break; } }

Also, here's my method print_crate. This writes out all the content, although the contents are stacking in a pile. How do I write the content so it writes the same items on the same line? ie

4 Cola

instead of

Cola

Cola

Cola

Cola

public void print_crate() { int keepshopping1 = 0; do { 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, myCrate.Length); int cnt = amountBottles; foreach (var sodabottles in myCrate) { if (sodabottles != null) Console.WriteLine(sodabottles); { cnt++; } /*else Console.WriteLine("Empty space");*/ }

Later on, I would like to have a method for sorting the bottles in myCrate by Price and Name and hopefully a search method too, where you can write "Cola", and it will write out how many Cola´s the crate holds.

The entire code:

using System; namespace sodacrate { /*public struct Bottles { }*/ class Bottles //create the class Bottles to gather information about the contents of the crate { string flavor;// = { "Cola", "Water", "Orange", "Raspberry", "GrapeTonic" }; int price; // 4, 5, 6, 7, 8 private string v1; private int v2; private int v3; //METOD: KONSTRUKTOR public Bottles(string flavor, int price) { this.flavor = flavor; this.price = price; } public Bottles(string v1, int v2, int v3) { this.v1 = v1; this.v2 = v2; this.v3 = v3; } //Property for flavor public string Flavor { get { return flavor; } set { flavor = value; } } //Property for 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]; private int amountBottles = 0; //Identifierare. Keep track of amount of bottles in myCrate public int crateValue = 0; //Total value of the crate content public int i { get; private set; } //public string[] flavor = new string[] { "Cola", "Water", "Orange", "Raspberry", "GrapeTonic" }; //The flavors of the beverages //private int i; 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"); //write this if other input than 0-6 i made break; } } while (temp != 0); } public void add_soda() { int adding = 0; do { //Console.Clear(); //menu for choosing flavor 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()); //input 0-5 and then ENTER to execute switch (adding) { case 1: myCrate[i] = new Bottles("Cola", 4); i++; Console.WriteLine("Cola"); break; case 2: myCrate[i] = new Bottles("Water", 5); i++; Console.WriteLine("Water"); break; case 3: myCrate[i] = new Bottles("Orange", 6); i++; Console.WriteLine("Orange"); break; case 4: myCrate[i] = new Bottles("Raspberry", 7); i++; Console.WriteLine("Raspberry"); break; case 5: myCrate[i] = new Bottles("GrapeTonic", 8); i++; Console.WriteLine("Grape Tonic"); break; default: Console.WriteLine("Incorrect Input"); break; } //Check if there´s space in the crate. If there´s already 25 bottles in the crate, write " - Your crate is full". for (int i = 0; i < 25; i++) { if (amountBottles == 25) { Console.WriteLine(" - Your crate is full!"); continue; } else { amountBottles++; break; } } }while (adding != 0); } public void print_crate() { int keepshopping1 = 0; do { 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, myCrate.Length); int cnt = amountBottles; foreach (var sodabottles in myCrate) { if (sodabottles != null) Console.WriteLine(sodabottles); { cnt++; } /*else Console.WriteLine("Empty space");*/ } keepshopping1 = int.Parse(Console.ReadLine()); switch (keepshopping1) { case 1: add_soda(); break; case 2: remove_soda(); break; case 0: //back to main menu 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 keepshopping2 = 0; do { Console.Clear(); Console.WriteLine("*******************************************************"); Console.WriteLine("** Cost of your Soda Crate **"); Console.WriteLine("*******************************************************"); Console.WriteLine(); for (int k = 0; k < myCrate.Length; k++) //value per bottle. As for now, every bottle costs 5 G. //i aim for having different costs of the bottles. Cola, 4G, Water 5G, Orange, 6G etcetera. crateValue = amountBottles * 5; { Console.WriteLine("This will be " + crateValue + " 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: //back to main menu break; default: Console.WriteLine("Incorrect Input"); //skrivs ut om annat än siffra 1,2 eller 0 anges. break; } } while (keepshopping2 != 0); //Keep in mind to NOT count empty spaces in the array } public void find_soda() //maybe another identifier? { //Search for a name //Could use the string-methods ToLower() or ToUpper() } public void sort_sodas() { //Able to sort the array holding bottles and with bubble sort int max = myCrate.Length; //Outer loop for complete [bottles] for (int i = 1; i < max; i++) { //Inner loop for row by row int nrLeft = max - i; for (int j = 0; j < (max - i); j++) { if (myCrate[j].Price > myCrate[j + 1].Price) { int temp = myCrate[j].Price; myCrate[j] = myCrate[j + 1]; myCrate[j + 1].Price = temp; } } } } public void SortBottlesByName() { //sort with lambda /*this.listBottles.Sort((obj1, obj2) => obj1.Name.CompareTo(obj2.Name) );*/ } public void SortBottlesByPrice() { //sort with lambda /*this.listBottles.Sort((obj1, obj2) => obj1.Price.CompareTo(obj2.Price) );*/ } public void remove_soda() { //enter code here } } class Program { public static void Main(string[] args) { var Sodacrate = new Sodacrate(); Sodacrate.Run(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } }

Permalänk
Medlem

Nu har jag inte orkat testa detta själv utan kollade bara igenom koden lite snabbt men tror att problemet är i klassen "SodaCrate".
Du instansierar en array som max får ha 25 element i sig när du skriver:
Bottles[] myCrate = new Bottles[25];
Försöker du då lägga till en 26:e flaska kommer den kasta just det exceptionet du ser ("IndexOutOfRangeException").

Antingen så ökar du värdet i Bottles[] till önskvärt värde eller så byter du till en typ som klarar av att dynamiskt öka värdet allt eftersom du fyller den med fler element. Kolla på typen List för detta.

Permalänk

Använd inte array, använd en klass som implementerar IList istället. T.ex. List. Då sköter klassen hanteringen av storleken på den interna arrayen åt dig.

Visa signatur

Live and let live.

Permalänk
Medlem
Skrivet av natte84:

Nu har jag inte orkat testa detta själv utan kollade bara igenom koden lite snabbt men tror att problemet är i klassen "SodaCrate".
Du instansierar en array som max får ha 25 element i sig när du skriver:
Bottles[] myCrate = new Bottles[25];
Försöker du då lägga till en 26:e flaska kommer den kasta just det exceptionet du ser ("IndexOutOfRangeException").

Antingen så ökar du värdet i Bottles[] till önskvärt värde eller så byter du till en typ som klarar av att dynamiskt öka värdet allt eftersom du fyller den med fler element. Kolla på typen List för detta.

Skrivet av GiveMeLibertyOrDeath1337:

Använd inte array, använd en klass som implementerar IList istället. T.ex. List. Då sköter klassen hanteringen av storleken på den interna arrayen åt dig.

Jag får tyvärr inte använda List för min lärare

Jag har ändrat lite i min kod nu och det känns bättre, men varje gång jag ska kolla innehållet i myCrate i metoden print_crate så får jag ett felmeddelande: An unhandled exception of type 'System.NullReferenceException' occurred in Sodacrate.exe

Additional information: Object reference not set to an instance of an object.

if (amountBottles < 26) { Console.WriteLine(amountBottles); switch (adding) { case 1: Bottles Cola = new Bottles("Cola", 4); myCrate[i] = Cola; i++; Console.WriteLine("Cola"); amountBottles++; break; case 2: Bottles Water = new Bottles("Water", 5); myCrate[i] = Water; i++; Console.WriteLine("Water"); amountBottles++; break; case 3: Bottles Orange = new Bottles("Orange", 6); myCrate[i] = Orange; i++; Console.WriteLine("Orange"); amountBottles++; break; case 4: Bottles Raspberry = new Bottles("Raspberry", 7); myCrate[i] = Raspberry; i++; Console.WriteLine("Raspberry"); amountBottles++; break; case 5: Bottles GrapeTonic = new Bottles("GrapeTonic", 8); myCrate[i] = GrapeTonic; i++; Console.WriteLine("Grape Tonic"); amountBottles++; break; default: Console.WriteLine("Incorrect Input"); break; } } else { Console.WriteLine("Your crate is full"); }

print_crate

public void print_crate() { int keepshopping1 = 0; do { 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 ); for (int i = 0; i < myCrate.Length; i++) { Console.WriteLine( myCrate[i].Flavor ); } /*int cnt = amountBottles; foreach (var amountBottles in myCrate) { if (amountBottles != null) Console.WriteLine(amountBottles); { cnt++; } /*else Console.WriteLine("Tom plats"); }*/ 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); //Missa inte hjälpkoden som finns i projektbeskrivningen //Där beskrivs hur man löser det med tomma positioner i vektorn }

Ska man ändra något i egenskaperna i min klass Bottles?

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 private string v1; private int v2; private int v3; //METOD: KONSTRUKTOR public Bottles(string flavor, int price) { this.flavor = flavor; this.price = price; } public Bottles(string v1, int v2, int v3) { this.v1 = v1; this.v2 = v2; this.v3 = v3; } //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); } }

Permalänk
Medlem

Kan du visa SodaCrate klassen också?
Ser inte att du ändrat i arrayn i den koden du visade.

Permalänk

Det hade varit lättare att hjälpa dig om du laddade upp din applikation till ett repository på GitHub: https://github.com/

Om du gör den public så är det gratis.

Visa signatur

Live and let live.

Permalänk
Medlem

Nu har jag ändrat i min kod och lyckats få det resultatet jag vill:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace sodacrate { public 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 private string v1; private int v2; private int v3; //METOD: KONSTRUKTOR public Bottles(string flavor, int price) { this.flavor = flavor; this.price = price; } public Bottles(string v1, int v2, int v3) { this.v1 = v1; this.v2 = v2; this.v3 = v3; } //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--; //tar bort den extra oidentifierade flaskan som alltid hamnar i backen när man kallar på 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() //OBS annan identifierare här, står den som void så returnerar den ju inget värde! { //Betyg C //Beskrivs i läroboken på sidan 147 och framåt (kodexempel på sidan 149) //Man ska kunna söka efter ett namn //Man kan använda string-metoderna ToLower() eller ToUpper() } public void sort_sodas() { } public void remove_soda() { //kod här } } 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); } } }

Dold text

Nu ska jag bara lyckas med att kunna sortera flaskorna efter namn och efter pris i metoden sort_soda.
Senare kunna söka efter en flaska efter både namn och pris.
Därefter kunna ta bort flaskor genom att först skriva in namn och därefter få frågan hur många av den sorten man vill ta bort.

Jag har experimenterat lite med IComparable i klassen Bottles, men utan framgång. Finns det en enkel väg med ex. Array.Sort?

Permalänk
Medlem
Skrivet av koffe_o:

Nu har jag ändrat i min kod och lyckats få det resultatet jag vill:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace sodacrate { public 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 private string v1; private int v2; private int v3; //METOD: KONSTRUKTOR public Bottles(string flavor, int price) { this.flavor = flavor; this.price = price; } public Bottles(string v1, int v2, int v3) { this.v1 = v1; this.v2 = v2; this.v3 = v3; } //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--; //tar bort den extra oidentifierade flaskan som alltid hamnar i backen när man kallar på 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() //OBS annan identifierare här, står den som void så returnerar den ju inget värde! { //Betyg C //Beskrivs i läroboken på sidan 147 och framåt (kodexempel på sidan 149) //Man ska kunna söka efter ett namn //Man kan använda string-metoderna ToLower() eller ToUpper() } public void sort_sodas() { } public void remove_soda() { //kod här } } 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); } } }

Dold text

Nu ska jag bara lyckas med att kunna sortera flaskorna efter namn och efter pris i metoden sort_soda.
Senare kunna söka efter en flaska efter både namn och pris.
Därefter kunna ta bort flaskor genom att först skriva in namn och därefter få frågan hur många av den sorten man vill ta bort.

Jag har experimenterat lite med IComparable i klassen Bottles, men utan framgång. Finns det en enkel väg med ex. Array.Sort?

tog en titt här: https://support.microsoft.com/en-us/kb/320727

du bör kunna göra något av det det här:

var myArr = new int[] { 1, 4, 5, 3, 2, 0, 6, 9, 9 }; Array.Sort(myArr, (x, y) => { if (x == y) return 0; if (x < y) return 1; return -1; });

edit: använde lambda i exemplet ovan vilket du kanske inte tittat på än, här är samma fast med en vanlig funktion istället.

private int SortIntDesc(int a, int b) { if (a == b) return 0; if (a < b) return 1; return -1; } var myArr = new int[] { 1, 4, 5, 3, 2, 0, 6, 9, 9 }; Array.Sort(myArr, SortIntDesc);

Visa signatur

| Ryzen 5800x | Asus prime x470 pro | Asus rtx 3080 tuf oc | Gskill 32gb 3,6ghz | aw3225qf |

Permalänk
Medlem
Skrivet av Ragin Pig:

tog en titt här: https://support.microsoft.com/en-us/kb/320727

du bör kunna göra något av det det här:

var myArr = new int[] { 1, 4, 5, 3, 2, 0, 6, 9, 9 }; Array.Sort(myArr, (x, y) => { if (x == y) return 0; if (x < y) return 1; return -1; });

edit: använde lambda i exemplet ovan vilket du kanske inte tittat på än, här är samma fast med en vanlig funktion istället.

private int SortIntDesc(int a, int b) { if (a == b) return 0; if (a < b) return 1; return -1; } var myArr = new int[] { 1, 4, 5, 3, 2, 0, 6, 9, 9 }; Array.Sort(myArr, SortIntDesc);

Jag är hemskt ledsen, men jag har ingen aning om hur jag ska implementera det i min kod

Permalänk
Medlem

@koffe_o
Hm det kanske blir tydligare med ett liknande objekt.

class Person { public string Name; public int Age; public Person(string name, int age) { Name = name; Age = age; } //jämförelse funktion public static int SortAgeAscending(Person pA, Person pB) { if (pA.Age == pB.Age) return 0; if (pA.Age > pB.Age) return 1; return -1; } //jämförelse funktion public static int SortNameAscending(Person pA, Person pB) { return string.Compare(pA.Name, pB.Name, StringComparison.InvariantCulture); } } var p1 = new Person("Nicklas", 10); var p2 = new Person("Sandra", 27); var p3 = new Person("Eva", 19); var persons = new Person[] { p1, p2, p3}; Array.Sort(persons, Person.SortAgeAscending); Array.Sort(persons, Person.SortNameAscending);

Visa signatur

| Ryzen 5800x | Asus prime x470 pro | Asus rtx 3080 tuf oc | Gskill 32gb 3,6ghz | aw3225qf |

Permalänk
Medlem