Switch and case with lists and arrays - c#

I have been trying to make a program where the user chooses one option and then I'm using a switch case for every option. My biggest problems are for case 1,2,4.
On case 1: Here I what the user to be able to input as many strings as he/she wants through a list.
on case 2:here I want the user to be able to input 4 strings through an array.
case 3: prints out all the strings from case 1(lists).
case 4: prints out all the strings from case 2(arrays).
case 5: quit program
I know that the code in case 1,2 and 4 is definitely wrong, but I can't seem to find any good answer on what to do, I have been searching the web for quite a while now.
here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ryggsäcken
{
class MainClass
{
public static void Main(string[] args)
{
bool running = true;//Ger ett booleskt värde till variabeln running för att kunna skapa en loop
while (running)//Här skapas loopen
{
Console.WriteLine("\nVälkommen till ryggsäcken!");
Console.WriteLine("\n[1] Lägg till flera föremål i stora facket");
Console.WriteLine("[2] Lägg till 4 föremål i lilla facket");
Console.WriteLine("[3] Skriv ut innehållet i stora facket");
Console.WriteLine("[4] Skriv ut inehållet i lilla facket");
Console.WriteLine("[5] Avsluta");
Console.Write("\nVälj: ");
int option = Convert.ToInt32(Console.ReadLine());//Konverterar från string till Int
switch (option)
{
case 1:
Console.Write("Lägg till föremål i ryggsäcken: ");
List<string> mylist = new List<string> { };
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
break;
case 2:
Console.WriteLine("Skriv in 4 föremål");
string[] answer = new string[5];
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
}
break;
case 3:
foreach (string item in mylist)
{
Console.WriteLine(item);
}
break;
case 4:
Console.Writeline(answer[i]);
break;
case 5:
running = false;
}
}
}
}
}

You need to intialise mylist and answer at the very top level of this class, not in the case(s). Then you need to put checks in cases 3&4 to make sure those values are initialized or have valid info or have more than one element in them, and then only print the list or answer. You can even put a then writeline statement to say "Hey, your variable is not yet initialised or you need to input values." or something to that extent.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ryggsäcken
{
public class MainClass
{
public static void Main(string[] args)
{
List<string> mylist = new List<string> { };
string[] answer = new string[5];
bool running = true;//Ger ett booleskt värde till variabeln running för att kunna skapa en loop
while (running)//Här skapas loopen
{
Console.WriteLine("\nVälkommen till ryggsäcken!");
Console.WriteLine("\n[1] Lägg till flera föremål i stora facket");
Console.WriteLine("[2] Lägg till 4 föremål i lilla facket");
Console.WriteLine("[3] Skriv ut innehållet i stora facket");
Console.WriteLine("[4] Skriv ut inehållet i lilla facket");
Console.WriteLine("[5] Avsluta");
Console.Write("\nVälj: ");
int option = Convert.ToInt32(Console.ReadLine());//Konverterar från string till Int
switch (option)
{
case 1:
Console.Write("Lägg till föremål i ryggsäcken: ");
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
mylist.Add(Console.ReadLine());
break;
case 2:
Console.WriteLine("Skriv in 4 föremål");
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
}
break;
case 3:
if (mylist.Count > 0)
foreach (string item in mylist)
{
Console.WriteLine(item);
}
break;
case 4:
if (answer.Length > 0)
for (int i = 0; i < answer.Length; i++)
{
Console.WriteLine(answer[i]);
}
break;
case 5:
running = false;
break;
}
}
}
}
}

You have to declare the list outside of the while-loop, otherwise it will get deleted after every run.
List<string> mylist = new List<string> ();
while(running)
...
In case 1 you should add a loop with an break statement like:
case 1:
Console.Write("Lägg till föremål i ryggsäcken: ");
while(true)
{
string lineEntered = Console.ReadLine();
//Now here comes the break operator
if(lineEntered == "stopImDone"){
break;
mylist.Add(lineEntered);
}
break;
}
case 4 should be more like
case 4:
foreach(string i in awnser){
Console.WriteLine(i);
break;
}
This way all of the strings entered will be displayed.

Related

Why are my vectors being reset instead of having their own value?

I'm studying programing right now and I need to make a "bus". I've got a vector with 25 spots and user will fill these with passengers. I've got a switch-case menu so you can choose if you want to add a passenger or get the full passenger list and so on. When I've entered about 5 passengers and want to get the passenger list everyone on the bus turns to 0 instead of the age I entered. I have no idea what's wrong?
Comments in the code are in Swedish.
{
class Buss
{
public int[] passagerare;
public int antal_passagerare ;
public void Run()
{
Console.WriteLine("Welcome to the awesome Buss-simulator");
do
{
Console.WriteLine("Välj alternativ");
Console.WriteLine("1: Lägg till passagerare");
Console.WriteLine("2: Skriv ut listan över passagerare");
Console.WriteLine("3: Skriv ut total åldern över passagerna");
Console.WriteLine("4: Skriv ut medelåldern över passagerarna");
Console.WriteLine("0: Avsluta programmet.");
string str = Console.ReadLine();
int temp = Convert.ToInt32(str);
switch (temp)
{
case 1:
Console.WriteLine("Lägg till passagerare (ange ålder endast)!");
add_passenger();
break;
case 2:
Console.WriteLine("Skriv ut gästlistan!");
print_buss();
break;
case 3:
Console.WriteLine("hejsan");
break;
case 4:
Console.WriteLine("hejsan");
break;
case 0:
Console.WriteLine("hejsan");
break;
}
//ska ändra så att om man väljer 0 så stängs programmet
} while (true);
//Här ska menyn ligga för att göra saker
//Jag rekommenderar switch och case här
//I filmen nummer 1 för slutprojektet så skapar jag en meny på detta sätt.
//Dessutom visar jag hur man anropar metoderna nedan via menyn
//Börja nu med att köra koden för att se att det fungerar innan ni sätter igång med menyn.
//Bygg sedan steg-för-steg och testkör koden.
}
//Metoder för betyget E
public void add_passenger()
{
passagerare = new int[25];
if (antal_passagerare < 25)
{
Console.WriteLine("Ålder på passagerare nr " + antal_passagerare);
string age = Console.ReadLine();
int age2 = Convert.ToInt32(age);
passagerare[antal_passagerare] = age2;
Console.WriteLine(passagerare[antal_passagerare]);
antal_passagerare++;
}
else
{
Console.WriteLine("Bussen är full!");
}
//Lägg till passagerare. Här skriver man då in ålder men eventuell annan information.
//Om bussen är full kan inte någon passagerare stiga på
}
public void print_buss()
{
for (int i = 0; i < antal_passagerare; i++)
{
Console.WriteLine(passagerare[i]);
}
}
// public int calc_total_age()
//{
//}
//public int calc_average_age()
//{
//}
public void find_age()
{
}
public void sort_buss()
{
}
}
class Program
{
public static void Main(string[] args)
{
var minbuss = new Buss();
minbuss.Run();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
If I am understanding this correctly, you are setting the array:
passagerare = new int[25];
to a new array every time you get into the add_passenger function so altthough you may actually set it the first time, the next time the user gets into the function, it'll be reset again.
If this is the case, the you can simply define it before you call this function and pass it as a parameter.
EDIT: In regards to your comment, you can define it in one of two palces.
1) You can create a constructor that sets the array to a length of [25] such as:
public Buss(){
passagerare = new int[25];
}
2) You can define it before you enter your switch statement and pass the array into to each function as a parameter.

how to prevent null reference exception when doing a linear search of array?

Hi I'm doing a beginners course C# and trying to prevent a nulllreference exception when searching in an array
I've made a small program which takes user string input and places it in an array. the array is also searchable through a menu but if I choose "search array" before there are anything added to the array, the program crashes during a null reference exception. Is there any way around this using tryparse?
switch (selection)
{
case 1://for loop för att lägga till grejer, stuff.length; ger att du kan lägga till 5 saker
for (int i = 0; i < stuff.Length; i++)
{
Console.Write("Lägg till ett föremål: ");
stuff[i] += Console.ReadLine();
}
break;
case 2://for loop som skriver ut innehåll
for (int i = 0; i < stuff.Length; i++)
{
Console.WriteLine(stuff[i]);
}
break;
case 3://linjär sökning av innehåll
Console.Write(" skriv in ett sökord");
string searchword = Console.ReadLine();
for (int i = 0; i < stuff.Length; i++)
{
if (stuff[i].ToUpper() == searchword.ToUpper())
Console.WriteLine("vi hittade" + stuff[i]);
}
break;
case 4://bryter loopen och programmet avslutas
isRunning = false;
break;
In the first case, I think you just want to initialize the items with what the user has typed:
for (int i = 0; i < stuff.Length; i++)
{
Console.Write("Lägg till ett föremål: ");
stuff[i] = Console.ReadLine();
}
If you use += (to concatenate the current item with the user entry), an exception will be thrown if stuff[i] is null.
In case 3, you have to check whether an item is null:
for (int i = 0; i < stuff.Length; i++)
{
if (stuff[i]?.ToUpper() == searchword.ToUpper())
Console.WriteLine("vi hittade" + stuff[i]);
}
Note that both issues would be fixed if you created the array this way:
string[] stuff = Enumerable.Repeat(string.Empty, 200).ToArray();
You can use Enumerable.Where() to find all matching elements using predicate and loop through it using ForEach to display items..
case 3://linjär sökning av innehåll
Console.Write(" skriv in ett sökord");
string searchword = Console.ReadLine();
var lstElementsFound = stuff.Where(x => x.ToUpper() == searchword.ToUpper());
foreach (var item in stuff)
{
Console.WriteLine("vi hittade" + item);
}
break;
Don't forget to import System.Linq.

Lists & arrays c#

Hello
I am doing a logbook, where there is a menu of different options. In menu 1, the user enters his post (Title and Post). In Menu 2 you will be able to view all saved posts. You should therefore be able to see ALL posts that have been written, but the only one shown is the last written post. Does anyone know how to solve this?
public static void Main(string[] args)
{
List<string[]> loggBok = new List<string[]> {};
string[] post = new string[2];
post[0] = "Titel";
post[1] = "Inlägg";
DateTime tiden = DateTime.Now;
Console.WriteLine(tiden);
bool isRunning = true;
while (isRunning)
{
Console.WriteLine("\n\tVälkommen till loggboken!");
Console.WriteLine("\t[1]Skriv ett inlägg: ");
Console.WriteLine("\t[2]Skriv ut alla inlägg");
Console.WriteLine("\t[3]Sök inlägg");
Console.WriteLine("\t[4]Avsluta programmet!");
Console.Write("\nVälj meny: ");
int nr;
int.TryParse(Console.ReadLine(), out nr);
switch (nr)
{
case 1:
Console.WriteLine("Skriv en titel till ditt inlägg: ");
post[0] = Console.ReadLine();
Console.WriteLine("Skriv ett inlägg: ");
post[1] = Console.ReadLine();
loggBok.Add(post);
break;
case 2:
foreach (string[] text in loggBok)
{
Console.WriteLine("\nHär är dina inlägg i loggboken:\n ");
Console.WriteLine("Inlägg:{0} " + "\n\t{1}", text);
}
break;
case 3:
Console.WriteLine("Skriv in ett ord för att söka bland dina inlägg");
string keyword = Console.ReadLine();
foreach (string[] text in loggBok)
{
if (post[0].Contains(keyword) || post[1].Contains(keyword))
{
Console.Write("\nTitel: " + post[0] + "\n" + post[1]);
}
}
break;
case 4:
isRunning = false;
break;
default:
Console.WriteLine("Försök igen, välj mellan 1-4!");
break;
}
}
}
You only ever create one post:
string[] post = new string[2];
That's at the top of Main, and you never replace it.
Every time you "add a post", you assign new values to that same array and add the same array object to the list all over again, so the list has many references to the same array object.
Instead, create a new array object for each new post:
case 1:
post = new string[2];
Console.WriteLine("Skriv en titel till ditt inlägg: ");
post[0] = Console.ReadLine();
Console.WriteLine("Skriv ett inlägg: ");
post[1] = Console.ReadLine();
loggBok.Add(post);
break;
I posted some comments under your code, here are the fixes:
You can move your input validation to the initial point where the user is entering the value, so you don't have to write out the full menu each time. This also means you can get rid of the default case, since we know the input is a number from 1 to 4:
int nr;
while (!int.TryParse(Console.ReadLine(), out nr) || nr < 1 || nr > 4)
{
Console.Write("Försök igen, välj mellan 1-4: ");
}
In case 1:, the line: string[] post = new string[2]; should be moved under case1 so you create a new post each time:
case 1:
Console.WriteLine("Skriv en titel till ditt inlägg: ");
string[] post = new string[2];
// rest of code omitted...
In case 2:, it looks like this line should be outside of the foreach loop, so it only prints once instead of once for every post:
case 2:
Console.WriteLine("\nHär är dina inlägg i loggboken:\n ");
foreach (string[] text in loggBok)
// rest of code omitted...
Also in case 2:, you have a bug here, I think: Console.WriteLine("Inlägg:{0} " + "\n\t{1}", text);. Since text is an array, you should reference the indexes 0 for title and 1 for post:
foreach (string[] text in loggBok)
{
Console.WriteLine("Inlägg:{0} " + "\n\t{1}", text[0], text[1]);
// rest of code omitted...
In case 3:, you are using text for your loop condition, but referencing post in the loop body. You should replace post with text:
case 3:
Console.WriteLine("Skriv in ett ord för att söka bland dina inlägg");
string keyword = Console.ReadLine();
foreach (string[] text in loggBok)
{
if (text[0].Contains(keyword) || text[1].Contains(keyword))
{
Console.Write("\nTitel: " + text[0] + "\n" + text[1]);
}
}
break;
All together, the changes would look like:
private static void Main()
{
List<string[]> loggBok = new List<string[]> {};
DateTime tiden = DateTime.Now;
Console.WriteLine(tiden);
bool isRunning = true;
while (isRunning)
{
Console.WriteLine("\n\tVälkommen till loggboken!");
Console.WriteLine("\t[1]Skriv ett inlägg: ");
Console.WriteLine("\t[2]Skriv ut alla inlägg");
Console.WriteLine("\t[3]Sök inlägg");
Console.WriteLine("\t[4]Avsluta programmet!");
Console.Write("\nVälj meny: ");
int nr;
while (!int.TryParse(Console.ReadLine(), out nr) || nr < 1 || nr > 4)
{
Console.Write("Försök igen, välj mellan 1-4: ");
}
switch (nr)
{
case 1:
Console.WriteLine("Skriv en titel till ditt inlägg: ");
string[] post = new string[2];
post[0] = Console.ReadLine();
Console.WriteLine("Skriv ett inlägg: ");
post[1] = Console.ReadLine();
loggBok.Add(post);
break;
case 2:
Console.WriteLine("\nHär är dina inlägg i loggboken:\n ");
foreach (string[] text in loggBok)
{
Console.WriteLine("Inlägg:{0} " + "\n\t{1}", text[0], text[1]);
}
break;
case 3:
Console.WriteLine("Skriv in ett ord för att söka bland dina inlägg");
string keyword = Console.ReadLine();
foreach (string[] text in loggBok)
{
if (text[0].Contains(keyword) || text[1].Contains(keyword))
{
Console.Write("\nTitel: " + text[0] + "\n" + text[1]);
}
}
break;
case 4:
isRunning = false;
break;
}
}
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
post is a reference type, That means that you're adding a reference to it when you add it to loggBok, the value doesn't get copied
You can solve this by instantiating a new string[] in case 1:
post = new string[2];
Console.WriteLine("Skriv en titel till ditt inlägg: ");
...

Add user input to Array in steps C#?

I've got a task in school saying that I'm supposed to create a program similar to a backpack where I'm supposed to use an array and a list.
Function of the backpack is to be able to put 4 objects into the smaller compartment (ytterfack) and then put unlimited amount of objects into the large compartment (stora facket).
I'd like it to work with a menu where the user can put one item into the (ytterfack) and if the user want to, switch over to the (stora fack) and put an item into that one. That is, I'm trying to avoid having a for-loop for the (ytterfack) which would mean that the user get the choice of puttin 4 objects strait away into the (ytterfack).
Is there a way to create an array and let the user put the elements inside one at a time and even get a message out when it's full?
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\tVälkommen till Ryggsäcken!!\n");
Console.WriteLine("\t[1] Lägg till ett föremål i det stora facket");
Console.WriteLine("\t[2] Lägg till ett föremål i ytterfacket");
Console.WriteLine("\t[3] Skriv ut innehållet i stora facket");
Console.WriteLine("\t[4] Skriv ut innehållet i ytterfacket");
Console.WriteLine("\t[5] Rensa innehållet i stora facket");
Console.WriteLine("\t[6] Rensa innehållet i ytterfacket");
Console.WriteLine("\t[7] Avsluta\n");
string[] ytterFack = new string[4];
List<string> storaFacket = new List<string> { };
int i = 0;
bool kör = true;
do
{
Console.Write("\n\tVälj punkt från menyn: ");
int menyVal = Convert.ToInt32(Console.ReadLine());
switch (menyVal)
{
case 1:
Console.Write("\n\tSkriv in ett föremål: ");
storaFacket.Add(Console.ReadLine());
//Console.WriteLine("\n\tDu har lagt in " + + " Tack!\n");
break;
case 2:
Console.Write("\n\tSkriv in ett föremål: ");
ytterFack[i] = Console.ReadLine();
//Console.WriteLine("\n\tDu har lagt in " + ytterFack[i] + " Tack!\n");
break;
case 3:
Console.WriteLine("\tInnehållet i stora facket är:");
foreach (string item in storaFacket)
{
Console.WriteLine("\t" + item);
}
break;
case 4:
Console.WriteLine("\tInnehållet i ytterfacket är:");
foreach (string item in ytterFack)
{
Console.WriteLine("\t" + item);
}
break;
case 5:
storaFacket.Clear();
Console.WriteLine("\tNu är stora facket tömt!\n");
break;
case 6:
Array.Clear(ytterFack, 0, ytterFack.Length);
Console.WriteLine("\tNu är ytterfacket tömt!\n");
break;
case 7:
kör = false;
break;
default:
break;
}
}
while (kör);
}
}
Instead of doing everything in Main(), start by modeling your BackPack as a separate class - this way you can implement and apply the constraints (like 4 items max) consistently, even if you use a List<string> for both:
public class BackPack
{
private List<string> ytterFacket = new List<string>();
public List<string> YtterFacket
{
get {
return ytterFacket;
}
}
private List<string> storaFacket = new List<string>();
public List<string> StoraFacket
{
get {
return storaFacket;
}
}
public string PutIntoYtterFacket(string item)
{
if (ytterFacket.Count < 4)
{
ytterFacket.Add(item);
return string.Format("Du har lagt in {0}! Tack!", item);
}
return string.Format("Kan inte lägge till {0}, gräns nådd", item);
}
public string PutIntoStoraFacket(string item)
{
storaFacket.Add(item);
return string.Format("Du har lagt in {0}! Tack!", item);
}
public string ClearYtterFacket()
{
ytterFacket.Clear();
return "Nu är ytterfacket tömt!";
}
public string ClearStoraFacket()
{
storaFacket.Clear();
return "Nu är storafacket tömt!";
}
}
So the case of adding to ytterFacket becomes (assuming fjallraven is an instance of the BackPack class):
Console.Write("\n\tSkriv in ett föremål: ");
fjallraven.PutIntoYtterFacket(Console.ReadLine());
You don't have to do error handling in the case block, the BackPack instance will do it for you! (Sorry for the error strings, my Swedish is a bit rusty)
Ok, this is what it became.
I would appreciate a comment or two about it, what can I do better or in a easier way??
Console.WriteLine("\tVälkommen till Ryggsäcken!!\n");
Console.WriteLine("\t[1] Lägg till ett föremål i det stora facket");
Console.WriteLine("\t[2] Lägg till ett föremål i ytterfacket");
Console.WriteLine("\t[3] Skriv ut innehållet i stora facket");
Console.WriteLine("\t[4] Skriv ut innehållet i ytterfacket");
Console.WriteLine("\t[5] Rensa innehållet i stora facket");
Console.WriteLine("\t[6] Rensa innehållet i ytterfacket");
Console.WriteLine("\t[7] Avsluta\n");
string[] ytterFack = new string[4];
List<string> storaFacket = new List<string> { };
int i = 0;
bool kör = true;
do
{
Console.Write("\n\tVälj punkt från menyn: ");
try
{
int menyVal = Convert.ToInt32(Console.ReadLine());
switch (menyVal)
{
case 1:
Console.Write("\n\tSkriv in ett föremål: ");
storaFacket.Add(Console.ReadLine());
//Console.WriteLine("\n\tDu har lagt in " + + " Tack!\n");
break;
case 2:
Console.Write("\n\tSkriv in ett föremål: ");
if (ytterFack[0] == null)
{
ytterFack[0] = Console.ReadLine();
break;
}
else if (ytterFack[1] == null)
{
ytterFack[1] = Console.ReadLine();
break;
}
else if (ytterFack[2] == null)
{
ytterFack[2] = Console.ReadLine();
break;
}
else if (ytterFack[3] == null)
{
ytterFack[3] = Console.ReadLine();
break;
}
else
{
Console.WriteLine("\n\tFacket är fullt och måste tömmas innan du kan lägga ner föremål här.");
break;
}
break;
case 3:
Console.WriteLine("\n\tInnehållet i stora facket är:\n");
foreach (string item in storaFacket)
{
Console.WriteLine("\t" + item);
}
break;
case 4:
Console.WriteLine("\n\tInnehållet i ytterfacket är:\n");
foreach (string item in ytterFack)
{
Console.WriteLine("\t" + item);
}
break;
case 5:
storaFacket.Clear();
Console.WriteLine("\n\tNu är stora facket tömt!\n");
break;
case 6:
Array.Clear(ytterFack, 0, ytterFack.Length);
Console.WriteLine("\n\tNu är ytterfacket tömt!\n");
break;
case 7:
kör = false;
break;
default:
Console.WriteLine("\n\tDu måste välja från menyn, [1] - [7]");
break;
}
}
catch
{
Console.WriteLine("\n\tDu kan bara mata in ett val (en siffra) från menyn!");
}
}
while (kör);
}

Program shuts down when array is full, Need a search and sort too

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'
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

Categories