So I tried making a todo list app making use of for loops and nested if statements. I created a function for adding tasks deleting and showing the whole list, but when I run the code I only get to input a task once even though I set the list capacity to what the user wants.
This is my code and what I've tried so far:
namespace mycsharpproject1
{
class Program
{
static void Main(string[] args)
{
List<string> todo = new List<string>();
void addt()
{
Console.WriteLine("enter task to be add");
todo.Add(Console.ReadLine());
}
void removet()
{
Console.WriteLine("enter task to be removed");
todo.Remove(Console.ReadLine());
}
void showt()
{
Console.WriteLine(todo);
}
string user_input = Console.ReadLine();
if (user_input == "r")
{
if (todo.Count == 0)
{
Console.WriteLine("you have no tasks in your list");
}
else
{
removet();
}
}
if (user_input == "a")
{
int i= Convert.ToInt32(Console.ReadLine());
if (i == todo.Capacity)
{
addt();
}
}
if (user_input == "s")
{
showt();
}
Console.ReadKey();
}
}
}
Modified your code a little bit. It's because there's no loop in your code, it only runs once. And the last like Console.ReadKey just reads an input and exits.
And the list doesn't need a capacity to be set if you exactly need that amount of item in yoru list. So, try this one.
class Program
{
static List<string> todo = null;
static void Main(string[] args)
{
todo = new List<string>();
while (true)
{
string user_input = Console.ReadLine();
if (user_input == "r")
{
if (todo.Count == 0)
{
Console.WriteLine("you have no tasks in your list");
}
else
{
removet();
}
}
if (user_input == "a")
{
addt();
}
if (user_input == "s")
{
showt();
}
}
}
static void addt()
{
Console.WriteLine("enter task to be add");
todo.Add(Console.ReadLine());
}
static void removet()
{
Console.WriteLine("enter task to be removed");
todo.Remove(Console.ReadLine());
}
static void showt()
{
todo.ForEach(q => Console.WriteLine(q));
}
}
Related
I'm currently trying to understand events in C # by writing my own custom event. My goal is to trigger an event after the user enters something into the console. if the string equals to "--start" something should happen. I am currently not reaching my breakpoint in the constructor of my custom event. I hope you can help me.
here is my code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Welcome to the BlackJack Console Game!{Environment.NewLine}" );
Console.WriteLine($"You get 500 Credits. The minimal Bet is 10 and the maximal 50!{Environment.NewLine}");
Console.WriteLine($"You can check your Creditcount with --credits{Environment.NewLine}");
Console.WriteLine($"To Start the Game write --start in the command line{Environment.NewLine}");
string userInput = Console.ReadLine();
Game game = new Game();
game.UserInput = userInput;
}
}
public class Game
{
public event EventHandler<UserInputEvent> UserWritedInput;
private string _userInput;
public string UserInput
{
get { return _userInput; }
set
{
_userInput = value;
OnUserWritedInput();
}
}
public void OnUserWritedInput()
{
UserWritedInput?.Invoke(this, new UserInputEvent(_userInput));
}
}
public class UserInputEvent : EventArgs
{
private string _userInput;
public UserInputEvent(string userInput)
{
this._userInput = userInput;
if (_userInput.Equals("--start"))
{
Console.WriteLine("game started!");
}
}
}
You haven't subscribed to the event:
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Welcome to the BlackJack Console Game!{Environment.NewLine}" );
Console.WriteLine($"You get 500 Credits. The minimal Bet is 10 and the maximal 50!{Environment.NewLine}");
Console.WriteLine($"You can check your Creditcount with --credits{Environment.NewLine}");
Console.WriteLine($"To Start the Game write --start in the command line{Environment.NewLine}");
string userInput = Console.ReadLine();
Game game = new Game();
game.UserWritedInput += OnUserWritedInput;
game.UserInput = userInput;
}
private void OnUserWritedInput(object sender, UserInputEvent args)
{
if (args.UserInput.Equals("--start"))
{
Console.WriteLine("game started!");
}
}
}
public class UserInputEvent : EventArgs
{
public string UserInput {get;}
public UserInputEvent(string userInput)
{
UserInput = userInput;
}
}
I am trying to write text in the same line with the colour changing mid way through the line. At the moment I have split it into two separate parts, changing the colour each time, just using Console.Write instead of WriteLine.
This is fine for procedural operations, but when I run async tasks, I am getting many synchronisation issues.
Is it possible change the text colour mid WriteLine without using external libraries?
Try this silly example out using a ConcurrentQueue:
public class Message
{
public List<MessagePart> parts = new List<MessagePart>();
public void Render()
{
parts.ForEach(p => p.Render());
}
public class MessagePart
{
public string text;
public ConsoleColor color;
public MessagePart(string text, ConsoleColor color)
{
this.text = text;
this.color = color;
}
public void Render()
{
Console.ForegroundColor = color;
Console.Write(text);
}
}
}
class Program
{
static bool pause = false;
static bool quit = false;
static ConcurrentQueue<Message> messages = new ConcurrentQueue<Message>();
static void Main(string[] args)
{
Console.WriteLine("Press Space to Pause/UnPause.");
Console.WriteLine("Press Enter to Quit when you are done.");
Console.WriteLine("Press Enter to Start...");
Console.ReadLine();
Task.Run(() => RenderLoop());
Task.Run(() => YellowAndBlue());
Task.Run(() => RedAndBlue());
while (!quit)
{
while (!Console.KeyAvailable)
{
System.Threading.Thread.Sleep(50);
}
switch(Console.ReadKey(false).Key)
{
case ConsoleKey.Enter:
quit = true;
break;
case ConsoleKey.Spacebar:
pause = !pause;
break;
}
}
}
static void YellowAndBlue()
{
Message msg = new Message();
msg.parts.Add(new Message.MessagePart("Yellow", ConsoleColor.Yellow));
msg.parts.Add(new Message.MessagePart(" and ", ConsoleColor.White));
msg.parts.Add(new Message.MessagePart("Blue", ConsoleColor.Blue));
msg.parts.Add(new Message.MessagePart(" make ", ConsoleColor.White));
msg.parts.Add(new Message.MessagePart("Green\r\n", ConsoleColor.Green));
while (!quit)
{
System.Threading.Thread.Sleep(25);
messages.Enqueue(msg);
while (pause)
{
System.Threading.Thread.Sleep(50);
}
}
}
static void RedAndBlue()
{
Message msg = new Message();
msg.parts.Add(new Message.MessagePart("Red", ConsoleColor.Red));
msg.parts.Add(new Message.MessagePart(" and ", ConsoleColor.White));
msg.parts.Add(new Message.MessagePart("Blue", ConsoleColor.Blue));
msg.parts.Add(new Message.MessagePart(" make ", ConsoleColor.White));
msg.parts.Add(new Message.MessagePart("Magenta\r\n", ConsoleColor.Magenta));
while (!quit)
{
System.Threading.Thread.Sleep(25);
messages.Enqueue(msg);
while (pause)
{
System.Threading.Thread.Sleep(50);
}
}
}
static void RenderLoop()
{
Message message;
while (!quit)
{
while (!messages.IsEmpty && !quit)
{
if (messages.TryDequeue(out message))
{
message.Render();
}
while (pause)
{
System.Threading.Thread.Sleep(50);
}
}
if (!quit)
{
messages.Enqueue(new Message() { parts = { new Message.MessagePart("Queue Emptied!\r\n", ConsoleColor.White) } });
System.Threading.Thread.Sleep(100);
}
}
}
}
Output (paused):
I am looking to access a list from different methods in the same class.Is there an easier way to access the movieTitle list without making a new list for each method? Do I have to make a reference to the list in every method? or should I put them all into a separate class all together? My overall goal is to have a option menu that gets input from the user and depending on the input calls a method to list all movies, add a movie to the list, and pick a random movie from the list.
class Program
{
static void Main(string[] args)
{
optionMenu();
Console.Read();
}
static void optionMenu()
{
Console.Write("(a)LIST MOVIES|(b)ADD Movie|(c)RANDOM MOVIE");
string ui = Console.ReadLine();
if (ui == "a") { printNames(); }
else if (ui == "b") { addMovie(); }
else if (ui == "b") { randomPickMovie(); }
else { optionMenu(); }
}
static void printNames()
{
List<string> movieTitles = new List<string>();
/*list.....
/ movieTitles.Add("Jurassic Park");
/..........
/..........
*/..........
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count;i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie()
{
Console.WriteLine("Enter a title:");
string newTitle = Console.ReadLine();
//I can't say...
//movieTitles.Add(newTitle);
//...? do I need to make an instance of the list?
}
static void randomPickMovie()
{
Random r = new Random();
int random = r.Next();
Console.WriteLine(movieTitle[random]);
//same here. How do I access the movie titles in the printName() method so
//I can randomly pick a movie from the list?
}
}
Below is one way make the movie list shared. This declares and initializes the list as a static member of the class (instead of a local variable in the methods).
This approach works well for simple programs, but having global state in a large program can be problematic because it becomes difficult to see which methods affect which global state so bugs can easily creep in. See below for another approach.
class Program
{
static void Main(string[] args)
{
...
}
static List<string> movieTitles = new List<string>();
static void optionMenu()
{
...
}
static void printNames()
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count;i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie()
{
movieTitles.Add(newTitle);
}
static void randomPickMovie()
{
...
}
}
Another approach is to pass the data from one method to another. This makes it more obvious to see what methods use the movieList. It also allows us to specify additional restrictions, e.g. you can see that printNames only needs a read-only version of the list so you know that printNames can't modify the list. This approach is a little more work but it's a good habit to get into because it reduces bugs in the long term.
class Program
{
static void Main(string[] args)
{
...
}
static void optionMenu()
{
List<string> movieTitles = new List<string>();
string ui = Console.ReadLine();
if (ui == "a") { printNames(movieTitles); }
else if (ui == "b") { addMovie(movieTitles); }
else if (ui == "b") { randomPickMovie(movieTitles); }
else { optionMenu(); }
}
static void printNames(IReadOnlyList<string> movieTitles)
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count;i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie(List<string> movieTitles)
{
movieTitles.Add(newTitle);
}
static void randomPickMovie(List<string> movieTitles)
{
...
}
}
See https://stackoverflow.com/questions/13295319/instance-field-vs-passing-method-parameter for another user's point of view on which approach is better.
as for me, I prefer doing it this way.
class Program
{
static void Main(string[] args)
{
Movie movie = new Movie();
int x = 0;
while (x < 1)
{
movie.optionMenu(); Console.Write("Do you want to exit?");
string response = Console.ReadLine();
if (response == "Y") { x = 1; }
}
Console.Read();
}
}
class Movie
{
public List<string> movieTitles { get; set; }
public Movie()
{
movieTitles = new List<string>();
}
public void optionMenu()
{
Console.Write("(a)LIST MOVIES|(b)ADD Movie|(c)RANDOM MOVIE");
string ui = Console.ReadLine();
if (ui == "a") { printNames(); }
else if (ui == "b") { addMovie(); }
else if (ui == "c") { randomPickMovie(); }
else { optionMenu(); }
}
public void printNames()
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < movieTitles.Count; i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
public void addMovie()
{
Console.WriteLine("Enter a title:");
string newTitle = Console.ReadLine();
if (newTitle != "")
{
movieTitles.Add(newTitle);
Console.WriteLine("New movie successfully added!");
}
else
{
Console.WriteLine("Cannot add empty movie. Add movie failed.");
}
}
public void randomPickMovie()
{
if (movieTitles.Count != 0)
{
Random r = new Random();
int random = r.Next(0, movieTitles.Count - 1);
Console.WriteLine(movieTitles[random]);
}
else { Console.WriteLine("Movie list is empty."); }
}
}
Answer for all your questions is create MovieTitles property of type List<string> and access it like this:
class Program
{
static void Main(string[] args)
{
optionMenu();
Console.Read();
}
static List<string> movieTitles;
static List<string> MovieTitles
{
get
{
if (movieTitles == null)
CreateMoviesList();
return movieTitles;
}
}
static void CreateMoviesList()
{
movieTitles = new List<string>();
/*list.....
/ movieTitles.Add("Jurassic Park");
/..........
/..........
*/
}
static void optionMenu()
{
Console.Write("(a)LIST MOVIES|(b)ADD Movie|(c)RANDOM MOVIE");
string ui = Console.ReadLine();
if (ui == "a") { printNames(); }
else if (ui == "b") { addMovie(); }
else if (ui == "b") { randomPickMovie(); }
else { optionMenu(); }
}
static void printNames()
{
Console.WriteLine("Movies in your list...");
for (int i = 0; i < MovieTitles.Count; i++)
{
Console.WriteLine("\t-" + movieTitles[i]);
}
}
static void addMovie()
{
Console.WriteLine("Enter a title:");
string newTitle = Console.ReadLine();
MovieTitles.Add(newTitle);
}
static void randomPickMovie()
{
Random r = new Random();
int random = r.Next();
Console.WriteLine(MovieTitles[random]);
}
}
CreateMoviesList() create list of movies only once and can be use to print movies, randon pick and add movies later on.
I'm trying to figure out why I am getting the error "Cannot assign to 'loggedIn' because it is a method group" within my menu method. Any help will be appreciated. Code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GmailClient
{
class Program
{
static string userName="";
static string passWord="";
public static bool loggedIn()
{
if (userName == "")
{
if (passWord == "")
{
return false;
}
else
{
return false;
}
}
else
{
return true;
}
}
static void Main(string[] args)
{
}
public static void menu()
{
Console.WriteLine("Loading menu.");
if ( loggedIn = false)
{
Console.WriteLine("__________Menu__________");
Console.WriteLine("1) Enter your Gmail credentials");
Console.WriteLine("2) Exit the Console");
Console.WriteLine("________________________");
Console.WriteLine("What do you want to do?");
int userchoice = Convert.ToInt32(Console.ReadLine());
if (userchoice == 1)
{
credentials();
}
else if (userchoice == 2)
{
Console.WriteLine("Hope to see you soon!");
Console.ReadKey();
Environment.Exit(0);
}
}
else if (loggedIn = true)
{
Console.WriteLine("__________Menu__________");
Console.WriteLine("1) Enter your Gmail credentials");
Console.WriteLine("2) Check your inbox");
Console.WriteLine("3) Send an e-mail");
Console.WriteLine("4) Exit the Console");
Console.WriteLine("________________________");
Console.WriteLine("What do you want to do?");
int userchoice = Convert.ToInt32(Console.ReadLine());
if (userchoice == 1)
{
credentials();
}
else if (userchoice ==2)
{
getMail();
}
else if (userchoice ==3)
{
sendMail();
}
else if (userchoice ==4)
{
Console.WriteLine("Hope to see you soon!");
Console.ReadKey();
Environment.Exit(0);
}
}
}
public static void credentials()
{
Console.WriteLine("Enter your Gmail address:");
userName = Console.ReadLine();
Console.WriteLine("Enter your Gmail password:");
passWord = Console.ReadLine();
}
public static void getMail()
{
Console.WriteLine("Loading inbox messages");
}
public static void sendMail()
{
Console.WriteLine("Under Construction");
}
}
}
Change if ( loggedIn = false) to if (!loggedIn()) and if (loggedIn = true) to if (loggedIn()).
Also, when using an if condition check, don't use a single equals =. = is assignment (e.g., You are assigning a value to a variable variable = "value"). Use double equals == when comparing (e.g., if (variable == true) ...).
In the case of your code, loggedIn is defined as a method/function. Your code was treating it as a property/variable.
I have a class with 2 queues - a and b.
When I insert values to the second queue(queue b) all values from the first one(queue a) are being removed.
Here is part of the class:
class SuperMarket
{
private Queue<string> a;
private Queue<string> b;
public SuperMarket()
{
this.a = new Queue<string>();
this.b = new Queue<string>();
}
public void InsertToA(string name)
{
this.a.Insert(name);
}
public void InsertToB(string name)
{
this.b.Insert(name);
}
this is the main program:
public static void Main(string[] args)
{
SuperMarket a = new SuperMarket();
Console.WriteLine("Enter Names For first");
string name = Console.ReadLine();
while (name.CompareTo("aaa") != 0)
{
a.InsertToA(name);
name = Console.ReadLine();
}
Console.WriteLine("Enter Names For second");
name = Console.ReadLine();
while (name.CompareTo("aaa") != 0)
{
a.InsertToB(name);
name = Console.ReadLine();
}
}
What might cause this effect?
Thank you very much!
After a few years later, I can easily answer my own question:
public void InsertToA(string name)
{
this.a.Enqueue(name);
}
public void InsertToB(string name)
{
this.b.Enqueue(name);
}
--> One should use Enqueue instead of Insert when working with generics in c#.