Add user input to Array in steps C#? - 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);
}

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.

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: ");
...

Linear search after assigning variables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have been making a program that has been working. But now i want to change the search function of the program to something simpler. This is what I have done: and the error message is use of unassigned local variable logg. To be clear, this is how I want the search function to look. Now I just need to figure out the variable thing.
full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Loggbok
{
class MainClass
{
public static void Main(string[] args)
{
DateTime tiden = DateTime.UtcNow; //Skriver ut tiden vid varje inlägg
bool running = true; //Ger ett booleskt värde till variabeln running för att kunna skapa en loop
List<string[]> loggbok = new List<string[]>(); //Här skapas listan som innehåller arrayen
while (running) //Här skapas loopen
{
Console.WriteLine("\n************************************");
Console.WriteLine("\nVälkommen till loggboken!");
Console.WriteLine("\n************************************");
Console.WriteLine("\n[1] Skriv nytt inlägg i loggboken");
Console.WriteLine("[2] Skriv ut alla loggar");
Console.WriteLine("[3] Sök inlägg i loggboken");
Console.WriteLine("[4] Radera innehåll i loggboken");
Console.WriteLine("[5] Avsluta loggboken");
Console.WriteLine("\n************************************");
Console.Write("\nVälj: ");
int option; //Int eftersom valet ska vara ett heltal
try
{
option = Int32.Parse(Console.ReadLine()); //testar så att inmatningen är av typen Int
}
catch
{
Console.WriteLine("Fel, du får bara skriva in nummer"); //Felmeddelande om inmatningen är en bokstav
continue;
}
switch (option)
{
case 1:
string[] logg = new string[2]; //Här deklareras arrayen
Console.WriteLine("\n************************************");
Console.WriteLine(tiden);
Console.WriteLine("Ange en Titel:");
logg[0] = Console.ReadLine(); //Här sparas titeln
Console.Clear();
Console.WriteLine("\n************************************");
Console.WriteLine("Skriv inlägg:");
logg[1] = String.Format("{0}{1}{2}", Console.ReadLine(), Environment.NewLine,
DateTime.Now.ToString(
"yyyy-MM-dd HH:mm:ss")); //Här sparas inlägget samt datum och tid, detta är möjligt tack vare formattering
loggbok.Add(logg);
break;
case 2:
foreach (string[] item in loggbok) //För att skriva ut alla items i loggboken
{
Console.WriteLine("\n--------------------------------------\n ");
Console.WriteLine(item[0]); //För att skriva ut titel
Console.WriteLine(item[1]); //För att skriva ut inlägg
Console.WriteLine("\n--------------------------------------\n ");
}
Console.ReadLine();
break;
case 3:
Console.WriteLine("\n************************************");
Console.WriteLine("Skriv in ett ord du vill söka efter i loggboken:");
string nyckelord = Console.ReadLine(); //Här sparas inmatningen av nyckelordet
for (int i = 0; i < logg.Length; i++)
{
if (logg[i] == nyckelord)
{
Console.WriteLine(logg[0]);
Console.WriteLine(logg[1]);
}
else
{
Console.WriteLine("Finns ej");
}
}
break;
case 4:
Console.WriteLine("\n************************************");
Console.WriteLine("Skriv titeln på det inlägg du vill ta bort:");
string title = Console.ReadLine(); //Sparar titeln på inlägget användaren vill radera
for (int x = 0; x < loggbok.Count; x++) //Loopa igenom varje titel
{
if (String.Equals(loggbok[x][0], title, StringComparison.OrdinalIgnoreCase)
) //Icke skiftlägeskänslig matchning av titeln.
{
loggbok.RemoveAt(x); //Matchning funnen.
}
else
{
Console.WriteLine("Titeln finns inte, återgår till huvudmenyn");
}
}
break; //Avsluta loopen.
case 5:
running = false; //Avslutar loopen och därmed programmet
break;
default:
Console.WriteLine(
"Nu blev det fel, välj mellan [1] [2] [3] [4] [5]"); //Felmeddelande om valet är någon annan siffra än de som menyn innehåller
break;
}
}
}
}
}
This is what I have done: and the error message is use of unassigned
local variable logg
all local variables must be assigned before control leaves the containing method.
It is declared in case 1
remove the string[] logg = new string[2]; from case 1 and insert it before the opening try block otherwise you won't be able to use the array throughout the other cases.
string[] logg = new string[2];//Här deklareras arrayen
try
{
option = Int32.Parse(Console.ReadLine());//testar så att inmatningen är av typen Int
}
...
...
...
Your question is not clear and should be improved.
Assuming the code is given exactly as it is, then you are using break out of a loop or switch block.
Correct and check if you still have problems.

Switch and case with lists and arrays

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.

c# How do I choose a random word in my dictionary that the person can guess on and for it also to say how many letters it is? [Hangman Game] [duplicate]

This question already has answers here:
Random entry from dictionary
(7 answers)
Closed 8 years ago.
I am currently making an Hangman game, and I have everything set except having it so for each turn the player is guessing on a random word, currently they can guess on all the words in my dictionary/wordbank, and also to tell the player how many letters the word has, Currently you can write random words in hope that you get the correct one. The only idea I have is o to use Random, but further then that and I'm lost.
Cheers.
class Program
{
static List<string> ordbank = new List<string>()
{
"Leksak", "Djur", "Organismer", "Mat", "Länder"
};
static bool runMenu = true; //kör menyn
static bool runGame = false; //kör spelet
static int numberOfTries = 2; //antal försök personen har på sig
static int wrongGuesses = 0; // hur många gånger har personen gissat fel
static int numWordsToPutIn = 1; //Lägga till ett extra ord till listan, skulle vilja göra så man kan lägga till fler än 1 åt gången.
static void Main(string[] args)
{
Console.WriteLine("Hänga gubbe!\n1) Lägg till ord\n2) Lista till alla ord\n3) Spela\n4) Avsluta");
do
{
Console.Write("Menu: ");
string menuInput = Console.ReadLine();
switch (menuInput.ToLower())
{
case "1":
Console.WriteLine("Du ska lägga till " + numWordsToPutIn + " ord nu.");
for (int i = 1; i <= numWordsToPutIn; i++)
{
Console.WriteLine("Lägg till ord " + i + ": ");
string wordInput = Console.ReadLine();
ordbank.Add(wordInput);
}
ordbank.Sort();
break; //Ifall man vill lägga till nytt ord till listan.
case "2":
Console.WriteLine("Nu skrivs alla orden ut: ");
if (ordbank.Count > 0)
{
foreach (string ord in ordbank)
{
Console.WriteLine(ord);
}
}
else
{
Console.WriteLine("Listan är tom. Fyll den först."); //Behövs denna nu när jag ändrade så ord redan finns?
}
break; //Skriver ut orden de lagt in.
case "3":
if (ordbank.Count == 0)
{
Console.WriteLine("Fyll ordlistan med " + numWordsToPutIn + " ord innan du börjar spelet");
break;
}
Console.WriteLine("Hur många fel får man ha: " + numberOfTries + " ");
Console.WriteLine("Då kör vi, gissa vilka ord som finns med");
runGame = true;
wrongGuesses = 0;
do
{
Console.Write("Gissa ord: ");
string guessedWord = Console.ReadLine();
if (ordbank.Contains(guessedWord))
{
ordbank.Remove(guessedWord);
//kolla om personen har vunnit
if (ordbank.Count == 0)
{
Console.WriteLine("Grattis du vann");
runGame = false;
}
else
{
Console.WriteLine("Wohoo det ordet fanns med, fortsätt!");
}
}
else
{
wrongGuesses++;
//kolla om personen har förlorat
if (wrongGuesses == numberOfTries)
{
runGame = false;
Console.WriteLine("Du förlorade.");
ordbank.Clear();
}
else
{
Console.WriteLine("Du gissade fel, du har " + (numberOfTries - wrongGuesses) + " försök kvar");
}
}
} while (runGame);
break;
case "4":
Console.WriteLine("Spelet avslutas nu...");
runMenu = false;
break;
default:
Console.WriteLine("Snälla välj ett tal mellan 1 - 4.");
break;
}
} while (runMenu == true);
}
}
}
You can use the Random class to generate pseudo-random numbers. Its Next method can be used to retrieve a random number between 0 (including) and a given max value (excluding).
If you use the word list's element count as the max value, you're computing a random index which is between 0 and (list length - 1). You can then retrieve your random word at that index:
var random = new Random();
// Compute a valid list index
int randomIndex = random.Next(ordbank.Count);
// Fetch the word at that index
string randomWord = ordbank[randomIndex];
Make sure to only create one instance of Random and to re-use it. Otherwise, you might notice that the same numbers could be generated over and over again if Random.Next is called in a loop.
This is obviously a course assignment of some sort, so i don't want to do it for you but the below code should give you a hint to the solution.
Add all of the below to your code and use appropriately.
int selectedWordIndex = 0;
Random rand = new Random();
void pickNewRandomWord(){
selectedWordIndex = rand.Next(ordbank.Count);
}
string getSelectedWord(){
return ordbank[selectedWordIndex];
}

Categories