How to implement a console menu having submenus in C# - c#

(C#) I am working on a program that is similar to RedBox which will have customer and manager functions. I am just trying to get all the menu's working correctly before I begin implementing more functions, but I am encountering an error that I can not seem to understand. My issue seems to be in the CustomerMenu() method and in the MainMenu() method. I have added all that I have so you can get the full picture. Any help is appreciated as I am still somewhat new so any tips are appreciated, thank you.
MainMenu();
Console.ReadKey();
}
static void MainMenu()
{
int userChoice = MainMenuChoice(); // Reading in the userChoice with the MenuChoice method
if (userChoice == 3) // if user enters 3, the program ends
{
Console.WriteLine("Thank you, Goodbye!");
}
while (userChoice != 3)
{
if (userChoice == 1)
{
Console.WriteLine("Welcome to the customer menu!\n"); // The customer menu is brought up if user enters 1
CustomerMenu();
}
if (userChoice == 2)
{
Console.WriteLine("Welcome to the manager menu!\n"); // The manager menu is brought up if user enters 2
//ManagerMenu();
}
userChoice = MainMenuChoice(); // program ends
if (userChoice == 3)
{
Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");
}
}
}
static int MainMenuChoice()
{
Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu
Console.WriteLine("Welcome to VideoMart at University Boulevard! \nAt VideoMart you are able to rent a variety of movies from many genres such as action, family, horror, etc!");
Console.WriteLine("\nPress 1 if you are a customer");
Console.WriteLine("\nPress 2 if you are a manager");
Console.WriteLine("\nPress 3 to Exit");
Console.WriteLine("-----------------------------------------------------------------------------------------------------------");
string choice = Console.ReadLine();
Console.WriteLine();
while (!(choice == "1" || choice == "2" || choice == "3")) // error checking
{
Console.WriteLine("Please try again");
Console.WriteLine("Press 1 if you are a customer");
Console.WriteLine("Press 2 if you are a manager");
Console.WriteLine("Press 3 to Exit");
choice = Console.ReadLine();
}
return int.Parse(choice);
}
}
static void CustomerMenu() {
int customerChoice = CustomerMenuChoice(); // Reading in the customerChoice into the CustomerMenuChoice method
if (customerChoice == 5) // if user enters 5, the program ends
{
Console.WriteLine("Thank you for using VideoMart!");
}
while (customerChoice != 5)
{
if (customerChoice == 1)
{
Console.WriteLine("Press 1 to view movies available to rent.\n"); // this option gives the user the opportunity to view all movies available to rent
//MoviesAvailable();
}
if (customerChoice == 2)
{
Console.WriteLine("Press 2 to rent a movie.\n"); // this option gives the user the opportunity to rent a movie, with email address
//RentMovie();
}
if (customerChoice == 3)
{
Console.WriteLine("Press 3 to view a list of movies you currently have rented.\n"); // this option gives the user the opportunity to view movies a user currently has rented, with email address
//RentMovie();
}
if (customerChoice == 4)
{
Console.WriteLine("Press 4 to return a movie rented.\n"); // this option gives the user the opportunity to return a movie rented
//RentMovie();
}
customerChoice = CustomerMenuChoice();
if (customerChoice == 5)
{
Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");
}
}
}
static int CustomerMenuChoice()
{
Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu
Console.WriteLine("Welcome to VideoMart at University Boulevard! \nBelow is a list of actions that can be performed by customers!");
Console.WriteLine("\nPress 1 to view movies available to rent.");
Console.WriteLine("\nPress 2 to rent a movie.");
Console.WriteLine("\nPress 3 to view a list of movies you currently have rented.");
Console.WriteLine("\nPress 4 to return a movie rented.");
Console.WriteLine("\nPress 5 to exit.");
Console.WriteLine("-----------------------------------------------------------------------------------------------------------");
string customerChoice2 = Console.ReadLine();
Console.WriteLine();
while (!(customerChoice2 == "1" || customerChoice2 == "2" || customerChoice2 == "3" || customerChoice2 == "4") || customerChoice2 == "5") // error checking
{
Console.WriteLine("\nPress 1 to view movies available to rent.");
Console.WriteLine("\nPress 2 to rent a movie.");
Console.WriteLine("\nPress 3 to view a list of movies you currently have rented.");
Console.WriteLine("\nPress 4 to return a movie rented.");
Console.WriteLine("\nPress 5 to exit.");
customerChoice2 = Console.ReadLine();
}
return int.Parse(customerChoice2);
}
}

Using a flat menu system
You can try this corrected and a little refactored.
We created a method to get the user choice, so repeat code is no more needed. We use uint because choice is positive and TryParse to convert the inputed string. It returns 0 in case of error, so that's fine here.
Also we use a lamda to print the choices strings to not repeat them.
Next we use a switch to manage choice so the code is more clean and maintainable.
The console is cleared between menus and we offer navigation between root and sub menus.
A future improvement is to create tables of menus headers, choices and associated methods... with a auto-menu manager that runs these tables. Just a little more complex but not too much. It can be done by creating some collections and a MenuManager class. With such thing, you will have a robust system with very few code and nothing repeated.
static void Test()
{
MainMenu();
}
static uint GetUserChoice(Action printMenu, int choiceMax)
{
uint choice = 0;
Action getInput = () =>
{
uint.TryParse(Console.ReadLine(), out choice);
};
getInput();
while ( choice < 1 || choice > choiceMax )
{
Console.WriteLine();
Console.WriteLine("Please try again");
printMenu();
getInput();
}
return choice;
}
static void MainMenu()
{
Action printMenu = () =>
{
Console.WriteLine("Press 1 if you are a customer");
Console.WriteLine("Press 2 if you are a manager");
Console.WriteLine("Press 3 to Exit");
};
Console.Clear();
Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu
Console.WriteLine("Welcome to VideoMart at University Boulevard!");
Console.WriteLine("At VideoMart you are able to rent a variety of movies from many genres such as action, family, horror, etc!");
Console.WriteLine();
printMenu();
Console.WriteLine("-----------------------------------------------------------------------------------------------------------");
uint choice = GetUserChoice(printMenu, 3);
switch ( choice )
{
case 1:
CustomerMenu();
break;
case 2:
//ManagerMenu();
break;
case 3:
Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");
break;
default:
throw new NotImplementedException();
}
}
static void CustomerMenu()
{
Action printMenu = () =>
{
Console.WriteLine("Press 1 to view movies available to rent.");
Console.WriteLine("Press 2 to rent a movie.");
Console.WriteLine("Press 3 to view a list of movies you currently have rented.");
Console.WriteLine("Press 4 to return a movie rented.");
Console.WriteLine("Press 5 to return to main menu.");
};
Console.Clear();
Console.WriteLine("-----------------------------------------------------------------------------------------------------------"); // introducing the user with the menu
Console.WriteLine("Below is a list of actions that can be performed by customers!");
Console.WriteLine();
printMenu();
Console.WriteLine("-----------------------------------------------------------------------------------------------------------");
Console.WriteLine();
uint choice = GetUserChoice(printMenu, 5);
switch ( choice )
{
case 1:
//MoviesAvailable();
break;
case 2:
//RentMovie();
break;
case 3:
//RentedMovies();
break;
case 4:
//ReturnMovie();
break;
case 5:
MainMenu();
break;
default:
throw new NotImplementedException();
}
}
Using an auto-menu manager
Here is the menu choice class:
public class MenuChoice
{
public string Title { get; private set; }
public Action Action { get; private set; }
public MenuChoice(string title, Action action)
{
Title = title;
Action = action;
}
}
Here is the menu class:
public class Menu
{
private readonly string Separator = new string('-', 100);
private string Header;
private List<MenuChoice> Choices;
private Menu Root;
public Menu(string header, List<MenuChoice> choices, Menu root)
{
Header = header;
Choices = choices;
Root = root;
}
private void Print()
{
for ( int index = 0; index < Choices.Count; index++ )
Console.WriteLine($"Press {index + 1} {Choices[index].Title}");
Console.WriteLine($"Press {Choices.Count + 1} to " +
$"{( Root == null ? "exit" : "go to previous menu" )}");
}
public void Run()
{
Console.Clear();
Console.WriteLine(Separator);
Console.WriteLine(Header);
Console.WriteLine();
Print();
Console.WriteLine(Separator);
uint choice = GetUserChoice();
if ( choice == Choices.Count + 1 )
if ( Root == null )
{
Console.WriteLine("Thank you for visiting VideoMart at University Boulevard, Goodbye!");
return;
}
else
Root.Run();
else
{
var action = Choices[(int)choice - 1].Action;
if ( action != null )
action();
else
{
Console.WriteLine("Not implemented yet, press a key to continue.");
Console.ReadKey();
Run();
}
}
}
uint GetUserChoice()
{
uint choice = 0;
Action getInput = () =>
{
uint.TryParse(Console.ReadLine(), out choice);
};
getInput();
while ( choice < 1 || choice > Choices.Count + 1 )
{
Console.WriteLine();
Console.WriteLine("Please try again");
Print();
getInput();
}
return choice;
}
}
Here is the menu manager class:
public class MenuManager
{
private Menu Root;
public MenuManager(Menu root)
{
Root = root;
}
public void Run()
{
Root.Run();
}
}
Here the menu manager initialization, using methods or another menu instead of null in choices:
var choicesMain = new List<MenuChoice>();
var choicesCustomer = new List<MenuChoice>();
var choicesManager = new List<MenuChoice>();
string headerMain = "Welcome to VideoMart at University Boulevard!" + Environment.NewLine +
"At VideoMart you are able to rent a variety of movies from many genres such as action, family, horror, etc!";
string headerCustomer = "Below is a list of actions that can be performed by customers!";
string headerManager = "Below is a list of actions that can be performed by managers!";
var root = new Menu(headerMain, choicesMain, null);
var menuCustomer = new Menu(headerCustomer, choicesCustomer, root);
var menuManager = new Menu(headerManager, choicesManager, root);
choicesMain.Add(new MenuChoice("if you are a customer", menuCustomer.Run));
choicesMain.Add(new MenuChoice("if you are a manager", menuManager.Run));
choicesCustomer.Add(new MenuChoice("to view movies available to rent.", null));
choicesCustomer.Add(new MenuChoice("to rent a movie.", null));
choicesCustomer.Add(new MenuChoice("to view a list of movies you currently have rented.", null));
choicesCustomer.Add(new MenuChoice("to return a movie rented.", null));
Now all to do is:
new MenuManager(root).Run();

Related

C#: How to find the total sum of arrays inside functions?

I have to create a function that enables me to enter data for every customer in a hardware store. The data that I should enter for every customer is: first name, last name, product bought and its price. This data should be stored in an array. Have this function declare a 1D container, have the user initialise this 1D container with the above data, and have the function return this 1D container back to MAIN. In MAIN, invoke this function three times to create data for 3 customers.
Afterwards, I need to create another function that takes all three 1D containers of customer data from MAIN as parameters and adds up all the prices of the products they bought. Have this function return the total cost back to MAIN. (This is where I'm stuck.)
Lastly, I need to create a procedure that takes the total cost returned to MAIN as parameter and figures out if this total price(set to a simple integer) is a prime number:
if the value is prime, print: "Customers win the Price"
otherwise, print: "Customers won't get the price"
I am stuck on the second function, I tried to do a C-style for loop, but it doesn't work.
I tried to add these three prices as array positions with indices but nothing.
This is the code I have:
using System;
namespace ghghh
{
class Program
{
public static string [] inputData()
{
Console.WriteLine("Please enter your first name: ");
string FirstName = Console.ReadLine();
Console.WriteLine("Please enter your last name: ");
string LastName = Console.ReadLine();
Console.WriteLine("Please enter the product you ahve bought: ");
string product = Console.ReadLine();
Console.WriteLine("Please enter the price: ");
string price = Console.ReadLine();
string[] info = new string[4] { FirstName, LastName, product, price };
return info;
}
public static void sumOfPrice(string[] arr)
{
for(int i = 0; i<arr.Length; i++)
{
string sum = arr[i] + arr[i] + arr[i];
}
}
public static void isTotalCostPrime(int n)
{
if(n %2 == 0)
{
Console.WriteLine("Customers wont get get the prize.");
}
else
{
Console.WriteLine("Customers win the prize");
}
}
public static void Main (string[] args)
{
string[] final = inputData();
sumOfPrice(final);
}
}
}
Here you go with a partial solution to your problem. I made the prices decimal numbers (because most currencies are decimalized). That precludes your prime test at the end.
I also included a quantity. I was tempted to take out the first and last names for each item (since it requires a lot of typing). All in all, though, this should give you enough to get started.
I start with a POCO class to hold the purchased items (POCO stands for "Plain Old CLR Object"; it's a class that consists purely of properties. It's a bit like an old-fashioned C struct.
public class PurchasedItem
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
I separated the user interface out into a separate class (for reasons of separation of concerns). You could easily collapse this into a single class:
public class ItemUserInterface
{
public static PurchasedItem PromptForItem()
{
var purchasedItem = new PurchasedItem();
Console.Write("What is your First Name (or type \"exit\" if complete)? > ");
var firstName = Console.ReadLine();
if (firstName.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
return null;
}
purchasedItem.FirstName = firstName;
Console.Write("What is your Last Name? > ");
purchasedItem.LastName = Console.ReadLine();
Console.Write("What did you purchase? > ");
purchasedItem.ProductName = Console.ReadLine();
purchasedItem.Quantity = PromptForInteger("How many did you buy");
purchasedItem.Price = PromptForDecimal("What was the price");
Console.WriteLine(""); //empty line
return purchasedItem;
}
public static void ShowPurchase (PurchasedItem item)
{
Console.WriteLine($"{item.FirstName} {item.LastName} bought {item.Quantity} of {item.ProductName} at {item.Price} each");
}
public static int PromptForInteger(string prompt)
{
while (true)
{
Console.Write(prompt + " > ");
var entered = Console.ReadLine();
if (int.TryParse(entered, out var result))
{
return result;
}
//otherwise error
Console.WriteLine("Sorry, you must enter a proper integer value");
}
}
public static decimal PromptForDecimal(string prompt)
{
while (true)
{
Console.Write(prompt + " > ");
var entered = Console.ReadLine();
if (decimal.TryParse(entered, out var result))
{
return result;
}
//otherwise error
Console.WriteLine("Sorry, you must enter a proper decimal value");
}
}
}
By the way, while (true) will loop forever unless you do something like return or break out of the loop. Notice that I prompt the user over and over again until he/she enters a correctly formatted number (for the number entries).
Finally, here's my Main routine:
var itemsList = new List<PurchasedItem>();
while (true)
{
var item = ItemUserInterface.PromptForItem();
if (item == null)
{
break;
}
itemsList.Add(item);
}
// at this point, everything is entered
var totalPurchasePrice = 0.00m;
var totalItemsCount = 0;
foreach (var item in itemsList)
{
ItemUserInterface.ShowPurchase(item);
totalPurchasePrice += (item.Quantity * item.Price);
totalItemsCount += item.Quantity;
}
Console.WriteLine($"Purchase Summary: {itemsList.Count} different items ({totalItemsCount} total items) for {totalPurchasePrice:C}");
Console.ReadLine(); //pause
}
If I run this program the output looks like:
What is your First Name (or type "exit" if complete)? > Fly
What is your Last Name? > Dog57
What did you purchase? > Cabbage
How many did you buy > 2
What was the price > 1.99
What is your First Name (or type "exit" if complete)? > Fly
What is your Last Name? > Dog57
What did you purchase? > Hammer
How many did you buy > 6
What was the price > abc
Sorry, you must enter a proper decimal value
What was the price > 10.55
What is your First Name (or type "exit" if complete)? > exit
Fly Dog57 bought 2 of Cabbage at 1.99 each
Fly Dog57 bought 6 of Hammer at 10.55 each
Purchase Summary: 2 different items (8 total items) for $67.28

Overriding the Pokemon name

I have Pokemon.cs here:
using System;
using System.Collections.Generic;
namespace PokemonPocket{
public class PokemonMaster{
public string Name {get;set;}
public int NoToEvolve {get; set;}
public string EvolveTo {get; set;}
public PokemonMaster(string name, int noToEvolve, string evolveTo){
this.Name = name;
this.NoToEvolve = noToEvolve;
this.EvolveTo = evolveTo;
}
}
}
and I have created this program here called Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
namespace PokemonPocket
{
class Program
{
static void Main(string[] args)
{
//PokemonMaster list for checking pokemon evolution availability.
List<PokemonMaster> pokemonMasters = new List<PokemonMaster>(){
new PokemonMaster("Pikachu", 2, "Raichu"),
new PokemonMaster("Eevee", 3, "Flareon"),
new PokemonMaster("Charmander", 1, "Charmeleon")
};
// Use "Environment.Exit(0);" if you want to implement an exit of the console program
PokemonMenu(pokemonMasters);
}
static void PokemonMenu(List<PokemonMaster> pokemans)
{
// From now on myDictionary is available for any menu option
var myDictionary = new Dictionary<string, string>();
while (true)
{ // <- loop until exit option (key 'Q') is pressed
Console.WriteLine("Welcome to Pokemon Pocket App!");
Console.WriteLine("(1). Add Pokemon to my pocket");
Console.WriteLine("(2). List Pokemon(s) in my pocket");
Console.WriteLine("(3). Check if I can evolve Pokemon");
Console.WriteLine("(4). Evolve Pokemon\n");
Console.Write("Please only enter [1,2,3,4] or Q to exit:");
char menu = Convert.ToChar(Console.ReadLine());
if (menu == '1')
{ //Part 1
Console.Write("Enter Pokemon Name :");
string name = Console.ReadLine();
Console.Write("Enter Pokemon HP : ");
int hp = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Pokemon EXP : ");
int exp = Convert.ToInt32(Console.ReadLine());
if (myDictionary.Count <= 0)
{
myDictionary.Add("Pokemon's Name", name);
myDictionary.Add("Pokemon's HP", hp.ToString());
myDictionary.Add("Pokemon's EXP", exp.ToString());
Console.WriteLine("Pokemon has been added!");
}
}
else if (menu == '2')
{ //Part 2
foreach (var v in myDictionary)
Console.WriteLine(string.Format("{1}: {0}", v.Value, v.Key));
}
else if (menu == '3') //Part 3
{
if (!myDictionary.TryGetValue("Pokemon's Name", out var myPokemon))
{
// No pokemon in pocket so just exit
Console.WriteLine("You have no pokemon!");
continue;
}
var matchedPokemon = pokemans.Find(p => p.Name == myPokemon);
if (matchedPokemon != default)
{
Console.WriteLine("Can evolve a pokeman!");
Console.WriteLine($"{matchedPokemon.Name} --> {matchedPokemon.EvolveTo}");
}
}
else if (menu == 'Q')
{
Console.WriteLine("App exited!");
Environment.Exit(0);
}
}
}
}
}
After adding the Pokemon in 1, when I input 2 this is what the program displays:
Pokemon's Name: Charmander
Pokemon's HP: 20
Pokemon's EXP: 30
When I input 4, I want the name to be overrided into Charmeleon, something like evolution in original Pokemon. Then when I input 2, I want it to display this:
Pokemon's Name: Charmeleon
Pokemon's HP: 0 //hp will become 0 when evolved
Pokemon's EXP: 0 //hp will become 0 when evolved
Pokemon's Skill = Solar power //skill will now be there as original input doesnt have skill
How do i do so?
You won't be able to update it, but you could do something like
Read in the pokemon's Value (TryGetValue)
Remove the existing Key (Remove)
Add the value back in with the new key (the new name) (Add)
Because Key of a Dictionary cannot be updated

How to use global variable for a two condition IF statement in C#

I want user to select from two options which will dictate what a single string says.
Eventually I will construct a sentence with the variables.
It may not make sense much and I'm totally new and doing this for my own enrichment. I know there is probably a lot better ways to construct this but I want to do most of it on my own as I can and have someone look at my finished project and explain what I could do and guide me at that point. First things first though.
I have a working version of this but it doesn't have IF statements with dual conditions. Also I have a class under the project for the construction of the variables and the main class program will generate the output.
class foodReport
{
public void appleSauce()
{
//apple sauce prompt
Console.WriteLine("Did you have apple sauce:");
Console.WriteLine("1. Yes");
Console.WriteLine("2. No");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//yes no if statement
if (KP.Key == ConsoleKey.NumPad1)
{
int hr = 1;
}
if (KP.Key == ConsoleKey.NumPad2)
{
int hr = 2;
}
}
public void whatEaten()
{
//food prompt
Console.WriteLine("What did you eat:");
Console.WriteLine("1. Sandwich");
Console.WriteLine("2. Candy");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//selection if statement
if (KP.Key == ConsoleKey.NumPad1)
{
string food = "A sandwich.";
}
if (KP.Key == ConsoleKey.NumPad2)
{
string food = "Some candy.";
}
}
public void outPut()
{
//WHERE IM HAVING TROUBLE
Console.WriteLine("Desert:");
Console.WriteLine("1. Cookie");
Console.WriteLine("2. Pie");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//selection if statement
if (KP.Key == ConsoleKey.NumPad1 && hr = 1)
{
string report = "You had apple sauce. " + food + " Also, a cookie'";
}
if (KP.Key == ConsoleKey.NumPad2)
{
string report = "You did not have apple sauce. " + food + " Also, a pie'";
}
}
The if (KP.Key == ConsoleKey.NumPad1 && hr = 1) throws error
Operator && cannot be applied to operands of type bool and int
the if (KP.Key == ConsoleKey.NumPad1 && hr = 1) throws error Operator
&& cannot be applied to operands of type bool and int
try "==": if (KP.Key == ConsoleKey.NumPad1 && hr == 1)

Rover And specimen C#

i am making a simple game of rover, in which i am having a simple problem which i can't figured out
This is my Main Function which is making One rover object in which rover can handle multiple device, there is one device which extract the specimen
Rover rov = new Rover();
string input;
//Device d = new Device();
//Specimen spec = new Specimen();
Console.WriteLine("Welcome to Planetary Rover");
Console.WriteLine("Enter y to start the game or n to exit");
string selection = Console.ReadLine();
if (selection == "y")
{
Console.WriteLine("Enter the rover Default Location X: ");
rov.X =
do
{
Console.WriteLine("Write the device nname to operate ");
input = Console.ReadLine();
rov.Handle(input);
//d.Operate();
} while (input != "end");
}
if (selection == "n")
{
Console.Clear();
}
else
{
Console.WriteLine("Wrong Input!");
}
THe drill is the device which extraxt the specimen whenever it is operated, it only extract if the specimen x and y is equals to rover x and y
I have done these thing but in my drill class there is operate functionwhich is doing the above thing, but problems occurs whenever drill is operating it is again making a new rover, so the rover x and y get null that time, so any can give me a potential fixes for that how can i use the existing rover in the drill function
public override void Operate(string ids)
{
Rover rov = new Rover();
if (specim.X == rov.X && specim.Y == rov.Y)
{
_wearfactor += 5;
Console.WriteLine("specimen extracted and wearfaction of drill is incresed by 5%");
Console.WriteLine(_wearfactor);
_spec. = 0;
}
if(specim.X != rov.X && specim.Y != rov.Y)
{
_wearfactor += 10;
Console.WriteLine("wear factor increased by 10%");
Console.WriteLine(_wearfactor);
}
if (_wearfactor == 100)
{
Console.WriteLine("Drill Destroyed");
Console.WriteLine("syart your program again");
Console.WriteLine("You can not drill specimen now");
this.Name = "";
}
}
You could change your Operate method's signature to:
public override void Operate(Rover rov, string ids)
then when you create Rover rov = new Rover(); you can pass it through for Operate to use.
Operate(rov, "ids");
Another option would be to make a public Rover object and directly reference it through Operate:
// assuming your main class is MainFunction
public class MainFunction()
{
public Rover rov { get; private set; }
public static void Main(string[] args)
{
// Establish the reusable rover
rov = new Rover();
// ...
}
}
Then in Operate, change all rov to MainFunction.rov

phone book in c#

I am a beginner in programming and I should prepare a phone book in console application as my project. I have written a code for some part of it, however I can't write a method for searching, editing, and deleting the information in the array list.
Here is the code and I appreciate if anyone help me on writing a code for bold parts which includes the method for search, edit, and delete.
thanks
class Program
{
static ArrayList tel_book_arr = new ArrayList();
static void Main(string[] args)
{
int sel=0;
while (sel != 6)
{
Console.Clear();
Console.WriteLine("1 : enter information");
Console.WriteLine("2 : display information");
Console.WriteLine("3 : search information");
Console.WriteLine("4 : edit information");
Console.WriteLine("5 : delete information");
Console.WriteLine("6 : exit");
Console.Write("\nenter your choose : ");
sel = Convert.ToInt32(Console.ReadLine());
switch (sel)
{
case 1:
enter_info();
break;
case 2:
show_info();
break;
case 3:
search_ifo();
break;
case 4:
edit_info();
break;
case 5:
delet_ifo();
break;
}
}
}
static void enter_info()
{
Console.Clear();
telephone t = new telephone();
Console.Write("enter name : ");
t.name = Console.ReadLine();
Console.Write("enter family : ");
t.family = Console.ReadLine();
Console.Write("enter tel : ");
t.tel = Console.ReadLine();
tel_book_arr.Add(t);
}
static void show_info()
{
Console.Clear();
foreach (telephone temp in tel_book_arr)
{
Console.WriteLine("name : " + temp.name);
Console.WriteLine("family : " + temp.family);
Console.WriteLine("tel : " + temp.tel);
Console.ReadKey();
}
}
static void search_ifo()
{
Console.Clear();
object name = Console.Read("please enter the number: ");
object family = Console.Read("please enter the family: ");
}
static void edit_info()
{
Console.Clear();
search_ifo();
}
static void delet_ifo()
{
Console.Clear();
}
}
class telephone
{
public string name, family, tel;
}
Don't use an ArrayList to store your data, use a different collection like a List<telephone> or a simple Dictionary
(see
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx for more information)
This will give you practical help
http://www.dotnetperls.com/dictionary
Have a look at this example
Dictionary<string, string> phonebook = new Dictionary<string, string>();
phonebook.Add("Fred", "555-5555");
phonebook.Add("Harry", "555-5556");
// See if Dictionary contains this string
if (phonebook.ContainsKey("Fred")) // True
{
string number = phonebook["Fred"];
Console.WriteLine(number);
}
// See if Dictionary contains this string
if (phonebook.ContainsKey("Jim"))
{
Console.WriteLine("Not in phonebook"); // Nope
}

Categories