How to create a counter that counts unrighteous inputs - c#

static void MainWindow()
{
Console.Clear();
Console.WriteLine("Menu");
Console.WriteLine("");
Console.WriteLine("1. Information");
Console.WriteLine("2. Contact");
Console.WriteLine("3. Extra");
Console.WriteLine("q. Exit");
string myOptions;
myOptions = Console.ReadLine();
switch (myOptions)
{
case "1":
Information();
break;
case "2":
Contact();
break;
case "3":
Extra();
break;
case "q":
Exit();
break;
default:
Console.Clear();
Console.WriteLine("Input is wrong");
Console.ReadKey();
MainWindow();
break;
}
Console.ReadLine();
}
I make a console menu and I need a counter that will count wrong entries. if it hits 5 times, the user is thrown back to the main menu.
I was trying to do this with while statement but it didnt work for me.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace ConsoleApp3
{
internal class Program
{
private static readonly IDictionary<char, Action> InputDictionary = new Dictionary<char, Action>
{
{ '1', Information },
{ '2', Contact },
{ '3', Extra },
{ 'q', Exit },
};
static void Main()
{
MainWindow();
}
private static void MainWindow()
{
var inputWasProcessed = false;
while (inputWasProcessed == false)
{
DisplayMainMenu();
var wrongEntries = 0;
while (wrongEntries < 5)
{
if (0 < wrongEntries)
{
Console.WriteLine($"Wrong Entries: {wrongEntries}");
}
inputWasProcessed = ProcessUserInput(Console.ReadKey().KeyChar);
if (inputWasProcessed == false)
{
wrongEntries++;
}
else
{
break;
}
}
}
Console.ReadLine();
}
private static void DisplayMainMenu()
{
Console.Clear();
Console.WriteLine("Menu");
Console.WriteLine();
Console.WriteLine("1. Information");
Console.WriteLine("2. Contact");
Console.WriteLine("3. Extra");
Console.WriteLine("q. Exit");
}
private static bool ProcessUserInput(char selectedOption)
{
if (InputDictionary.TryGetValue(selectedOption, out var action))
{
Console.WriteLine();
Console.WriteLine();
action.Invoke();
return true;
}
Console.Clear();
Console.WriteLine("Input is wrong.");
Console.WriteLine("Try again.");
return false;
}
private static void Information()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Contact()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Extra()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Exit()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
#region For Demonstration Purposes Only
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetCurrentMethod() // https://stackoverflow.com/a/2652481/109941
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
#endregion
}
}

Related

How to set default capacity for lists

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

New programmer here. How do I utilize constructs to create instances of a class (if that's what it's called)? Please see my example

A friend and I are doing a programming school project, but we're both new programmers and feel as if we're stuck. For the project we have to create a bank system where you have different options, eg. creating an account, transfering money and so on. However, we're not sure how to utilize the constructor to create an instance of the class. This is what we've got so far.
The constructor and a method for creating an account identifier:
public class Account
{
public int accountID;
public bool accountStatus;
public string[] accountInformation;
private string[] accountSettings;
private string[] debitCardInformation;
private string[] transferHistory;
private double accountBalance;
private double accountLoan;
private double accountDebt;
private double retirementSavings;
public Account(string firstName, string lastName, double startBalance)
{
this.accountID = AccountID();
this.accountStatus = true;
this.accountInformation = new string[] {firstName, lastName};
this.accountSettings = new string[] { };
this.accountBalance = startBalance;
this.accountLoan = 0;
this.accountDebt = 0;
this.retirementSavings = 0;
}
public static int AccountID()
{
Random rn = new Random();
int newAccountID = rn.Next(000000001, 999999999);
return newAccountID;
}
}
The program:
namespace ConsoleApp14
{
class Program
{
static public List<Account> accounts = new List<Account>();
static public int nextID = 0;
static void Main(string[] args)
{
Intro();
Actions();
}
public static void Intro()
{
Console.WriteLine("Please choose one of the following options:\n");
Console.WriteLine("Press '1' to create a new account.");
Console.WriteLine("Press '2' to log in to an existing one.\n");
int accessSystem = Convert.ToInt16(Console.ReadLine());
if (accessSystem == 1)
{
//LogIn();
}
else if (accessSystem == 2)
{
//CreateAccount();
}
else
{
Console.Clear();
Intro();
}
Console.Clear();
}
public static void Actions()
{
Console.WriteLine("Please choose one of the following options:\n");
string[] options = new string[12]
{
"Press '1' to switch between accounts.", "Press '2' to check your balance.", "Press '3' to check your debt.",
"Press '4' to check your loans.", "Press '5' to check your account's status (activated/deactivated).",
"Press '6' to check your account's information.", "Press '7' to check your debit card information.",
"Press '8' to check your account's settings.", "Press '9' to withdraw money.", "Press '10' to transfer money.",
"Press '11' to check your transfer history.", "Press '12' to check your retirement savings."
};
for (int i = 0; i < options.Length; i++)
{
Console.WriteLine(options[i]);
}
Console.WriteLine();
Account test = new Account("Test", "Testerson", 100);
int responseIndex = Convert.ToInt16(Console.ReadLine());
switch (responseIndex)
{
case 1:
//ChangeAccount();
break;
case 2:
//CheckAccountBalance();
break;
case 3:
//CheckAccountDebt();
break;
case 4:
//CheckAccountLoans();
break;
case 5:
//CheckAccountStatus();
break;
case 6:
//CheckAccountInformation();
Console.WriteLine("Endnu ikke implementeret");
break;
case 7:
//CheckDebitCardInformation();
break;
case 8:
//CheckAccountSettings();
break;
case 9:
//WithdrawMoney();
break;
case 10:
//TransferMoney();
break;
case 11:
//CheckTransferHistory();
break;
case 12:
//CheckRetirementSavings();
break;
default:
Console.Clear();
Actions();
return;
break;
}
}
public static void LogIn()
{
}
public static void CreateAccount()
{
}
}
}
I think what you mean is something like this
namespace ConsoltedeTEstes
{
class Program
{
public static void Main(string[] args)
{
//new list of accounts
List<Account> accounts = new List<Account>();
//add a new account on the list
accounts.Add(CreateAccount("first name", "last name", 10));
//Create a single instance using the method
Account accountTeste = CreateAccount("first name", "last name", 15);
}
public static Account CreateAccount(string firstName, string lastName, double startBalance)
{
return new Account(firstName, lastName, startBalance);
}
}
public class Account
{
public int accountID;
public bool accountStatus;
public string[] accountInformation;
private string[] accountSettings;
private string[] debitCardInformation;
private string[] transferHistory;
private double accountBalance;
private double accountLoan;
private double accountDebt;
private double retirementSavings;
public Account(string firstName, string lastName, double startBalance)
{
this.accountID = AccountID();
this.accountStatus = true;
this.accountInformation = new string[] { firstName, lastName };
this.accountSettings = new string[] { };
this.accountBalance = startBalance;
this.accountLoan = 0;
this.accountDebt = 0;
this.retirementSavings = 0;
}
public static int AccountID()
{
Random rn = new Random();
int newAccountID = rn.Next(000000001, 999999999);
return newAccountID;
}
}
}
But note that the Method is literally doing the exact same thing of the constructor

How to improve my menu (console) in c #

I created a menu with sub menus in console. Everything works fine but I wonder if it is not possible to improve the structure of my program. To simplify it and make it more generic.
class MainClass
{
public static void Main(string[] args)
{
MainMenu();
}
public static void MainMenu()
{
Console.WriteLine("Main Menu");
Console.WriteLine("--------------------");
Console.WriteLine("[1] Show activities");
Console.WriteLine("[2] Show teachers");
Console.WriteLine("[3] Show students");
Console.WriteLine("[4] Exit the program");
Console.WriteLine("--------------------\n");
Console.WriteLine("Please select an option from 1-4\n");
string choice = Console.ReadLine();
int number;
bool result = Int32.TryParse(choice, out number);
if (result)
{
Console.Clear();
SubMenu(number);
}
else
{
Console.WriteLine("Incorrect choice");
}
}
public static void SubMenu(int mainMenuChoice)
{
switch (mainMenuChoice)
{
case 1:
Console.WriteLine("Activities");
Console.WriteLine("[1] Show all activities");
Console.WriteLine("[2] Find a activity by his code");
Console.WriteLine("[3] Return Main Menu");
Console.WriteLine("[4] Exit the program");
Console.WriteLine("--------------------\n");
Console.WriteLine("Please select an option from 1-4\n");
break;
case 2:
Console.WriteLine("Teachers");
Console.WriteLine("[1] Show all teachers");
Console.WriteLine("[2] Find a teacher by his matricule");
Console.WriteLine("[3] Return Main Menu");
Console.WriteLine("[4] Exit the program");
Console.WriteLine("--------------------\n");
Console.WriteLine("Please select an option from 1-4\n");
break;
case 3:
Console.WriteLine("Students");
Console.WriteLine("[1] Show all students");
Console.WriteLine("[2] Find a student by his matricule");
Console.WriteLine("[3] Return Main Menu");
Console.WriteLine("[4] Exit the program");
Console.WriteLine("--------------------\n");
Console.WriteLine("Please select an option from 1-4\n");
break;
case 4:
Environment.Exit(0);
break;
}
string choice = Console.ReadLine();
int number;
bool result = Int32.TryParse(choice, out number);
if (result)
{
Action(mainMenuChoice, number);
}
else
{
Console.WriteLine("Incorrect choice");
}
}
public static void Action(int menu, int choice)
{
switch (menu)
{
case 1:
switch (choice)
{
case 1:
// Do Stuff
break;
case 2:
// Do Stuff
break;
case 3:
Console.Clear();
MainMenu();
break;
case 4:
Environment.Exit(0);
break;
}
break;
case 2:
switch (choice)
{
case 1:
// Do Stuff
break;
case 2:
// Do Stuff
break;
case 3:
Console.Clear();
MainMenu();
break;
case 4:
Environment.Exit(0);
break;
}
break;
case 3:
switch (choice)
{
case 1:
// Do Stuff
break;
case 2:
// Do Stuff
break;
case 3:
Console.Clear();
MainMenu();
break;
case 4:
Environment.Exit(0);
break;
}
break;
}
}
}
Currently if I have to add a sub menu, I have to add a line to the MainMenu() function, I must add a case in the SubMenu() function and as many as there are choices for this menu in Action().
For only one sub menu it's ok but if I have to add a dozen it quickly becomes unmanageable.
I should probably go through one or more classes but I'm lost on the structure.
I made something quickly to demonstrate one approach to the problem. I commented most of the code, but ask if anything is unclear. The main advantage to me is that you can declare your menus in one place as objects. In my code I have done this explicitly in the Main method, but you could easily write a factory method to generate menus for you.
class Program
{
//represents a line/option in a menu
class MenuItem
{
// displayed in the menu
public string Text { get; set; }
//is there a sub menu
public bool HasSubMenu { get; set; }
// if there's a submenu, what's its id
public int? SubMenuId { get; set; }
//if there isn't a sub menu, what should we do
public Action Action { get; set; }
}
//represents one menu i.e. a collection of options
class Menu
{
public Menu()
{
MenuItems = new List<MenuItem>();
}
public int MenuId { get; set; }
public List<MenuItem> MenuItems { get; set; }
public string Title { get; set; }
public void PrintToConsole()
{
foreach (MenuItem item in MenuItems)
{
Console.WriteLine(MenuItems.IndexOf(item) + " : " + item.Text);
}
}
}
//represents all the menus
class MenuCollection
{
public MenuCollection()
{
Menus = new List<Menu>();
}
public List<Menu> Menus { get; set; }
public void ShowMenu(int id)
{
//get the menu we want to display and call its PrintToConsole method
var currentMenu = Menus.Where(m => m.MenuId == id).Single();
currentMenu.PrintToConsole();
//wait for user input
string choice = Console.ReadLine();
int choiceIndex;
//once we have the users selection make sure its an integer and in range of our menu options
//if not then show an error message and re-display the menu
if (!int.TryParse(choice, out choiceIndex) || currentMenu.MenuItems.Count < choiceIndex || choiceIndex < 0)
{
Console.Clear();
Console.WriteLine("Invalid selection - try again");
ShowMenu(id);
}
else
{
// if the selection is good, then retrieve the corresponding menu item
var menuItemSelected = currentMenu.MenuItems[choiceIndex];
// if there's a sub menu then display it
if (menuItemSelected.HasSubMenu)
{
Console.Clear();
ShowMenu(menuItemSelected.SubMenuId.Value);
}
// otherwise perform whatever action we need
else
{
menuItemSelected.Action();
}
}
}
}
static void Main(string[] args)
{
// build a collection of menus
// can have as deep a structure as you like
// give each menu a unique integer MenuId
// link to other menus by setting HasSubMenu to true, and the SubMenuId to the MenuId of the menu you wish to link to
// or, set HasSubMenu to false, and have an Action performed when the menuitem is selected
MenuCollection collection = new MenuCollection()
{
Menus =
{
new Menu()
{
MenuId = 1,
MenuItems =
{
new MenuItem()
{
Text = "Go to sub menu",
HasSubMenu = true,
SubMenuId = 2
},
new MenuItem()
{
Text = "Print Action",
HasSubMenu = false,
Action = () =>
{
Console.WriteLine("I printed from an action");
}
}
}
},
new Menu()
{
MenuId = 2,
MenuItems =
{
new MenuItem()
{
Text = "Sub menu option 1",
HasSubMenu = false,
Action = () =>
{
Console.WriteLine("Printed from a sub menu");
}
},
new MenuItem()
{
Text = "Back to the top menu",
HasSubMenu = true,
SubMenuId = 1
}
}
}
}
};
collection.ShowMenu(1);
Console.ReadLine();
}
}
I have been making a lot of small CLI tools recently, I only fleshed out Activities, but here's an example of the approach I generally like to take for lots of branching menus/logic:
class Program
{
static T GetChoice<T>(List<Tuple<string, T>> choices)
{
var i = 1;
choices.ForEach(x => Console.WriteLine($"[{i++}]: {x.Item1}"));
var choiceIndex = int.Parse(Console.ReadLine());
return choices[choiceIndex - 1].Item2;
}
static void Main(string[] args)
{
Console.WriteLine("Main Menu: ");
var choices = new List<Tuple<string, Action>>()
{
new Tuple<string, Action>("Show Activities", ShowActivities),
new Tuple<string, Action>("Show Teachers", ShowTeachers),
new Tuple<string, Action>("Show Students", ShowStudents),
new Tuple<string, Action>("Exit", Exit),
};
GetChoice(choices)();
}
static void ShowActivities()
{
Console.WriteLine("Activities: ");
var choices = new List<Tuple<string, Action>>()
{
new Tuple<string, Action>("Show all activities", ShowAllActivities),
new Tuple<string, Action>("Find activity by code", FindActivityByCode),
new Tuple<string, Action>("Return to main menu", () => { Main(null); }),
new Tuple<string, Action>("Exit the program", Exit),
};
GetChoice(choices)();
}
static void ShowTeachers()
{
Console.WriteLine("Teachers: ");
var choices = new List<Tuple<string, Action>>();
}
static void ShowStudents()
{
Console.WriteLine("Students: ");
var choices = new List<Tuple<string, Action>>();
}
static void ShowAllActivities()
{
//Do stuff
}
static void FindActivityByCode()
{
//Do stuff
}
static void ReturnToMainMenu()
{
//Do stuff
}
static void Exit()
{
Environment.Exit(0);
}
}

Accessing list from method in another method

I would like to access list (in my program named "section") inside a method(menu choose). I tried 3 ways:
public static void dataBase()
{
List<float> section = new List<float>();
}
// 1st try
// List<float> section = new List<float>();
//
public static void mainMenu()
{
Console.Clear();
Console.WriteLine("Trans->Connector->\n");
Console.WriteLine("Add: \n1. Section \n2. Wled \n3. Regenerator");
menuChoose();
}
public static void menuChoose()
{
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
dataBase.section.Add();
section.Add(result);
break;
case ConsoleKey.D2:
Console.WriteLine("2");
break;
case ConsoleKey.D3:
Console.WriteLine("3");
break;
default:
Console.WriteLine("default");
break;
}
}
static void Main(string[] args)
{
int WeldCount;
int ConnectroCount;
//3rd try
// List<float> section = new List<float>();
//
mainMenu();
}
Thank you for your time!
You can't access a member in the local scope of your function outside it. You might want to think about making it a private instance variable inside your class that you will then be able to access from any method declared that belongs to this class, something along these lines:
public class MyClass
{
// this field is accessible from any method declared within this class
private List<Float> section;
public MyClass()
{
section = new List<Float>();
}
private void someMethod()
{
section.Add(2.2);
Console.WriteLine(section[0]); // example
}
}
Well you can make it class level variable (like in your 1st try) and make it static.
However you should use return value from your menuChoose() method. Having all code depend on single static list instance is not ideal.
public static List<float> menuChoose()
{
List<float> selection = new List<float>();
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
selection.Add(result);
break;
case ConsoleKey.D2:
Console.WriteLine("2");
break;
case ConsoleKey.D3:
Console.WriteLine("3");
break;
default:
Console.WriteLine("default");
break;
}
return selection;
}
You can to it, if you would implement something like this:
public static class DataBase
{
public static List<float> Section { get; set; }
static DataBase()
{
Section = new List<float>();
}
}
here how to use e.g. in your switch statement:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
DataBase.Section.Add(result);
break;
I didn't get what you try to achieve by dataBase.section.Add(); so I removed it in my example.
I could not use any of your answers so I did this in my way(much worse than yours, for sure)
public class Program
{
public int WeldCount;
public int ConnectroCount;
public List<float> section = new List<float>();
//public List<> TrackElements = new List<>();
public Program()
{
section.Add(0);
}
public void showResults()
{
float allSections = 0;
foreach (float item in section)
{
allSections += item;
}
Console.Clear();
Console.WriteLine("c1 {0}, c2 {1}, c3{2}", WeldCount,ConnectroCount,allSections);
Console.ReadKey();
}
public void finalConstruction()
{
}
public static void mainMenu()
{
Console.Clear();
Console.WriteLine("\n");
Console.WriteLine("Add: \n1. Section \n2. Weld \n3. Regenerator\n4. Show results");
}
public void menuChoose()
{
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
section.Add(result);
mainMenu();
menuChoose();
break;
case ConsoleKey.D2:
WeldCount++;
mainMenu();
menuChoose();
break;
case ConsoleKey.D3:
ConnectroCount++;
mainMenu();
menuChoose();
break;
case ConsoleKey.D4:
showResults();
mainMenu();
menuChoose();
break;
default:
Console.WriteLine("wtf did just happend");
break;
}
}
static void Main(string[] args)
{
Program program = new Program();
mainMenu();
program.menuChoose();
}
}
}

Gmail console App C#

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.

Categories

Resources