phone book in c# - 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
}

Related

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 implement a console menu having submenus in 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();

Using enums and switch c# [duplicate]

This question already has answers here:
Convert a string to an enum in C#
(29 answers)
Closed 5 years ago.
I have some problems with using enums with switch.My task is to enter the name of the country and then show which part of the world is that one. I can't read enums from the keyboard.Did I make mistakes?Thanks for the help.
`
class Program
{
enum Country{ Spain,USA,Japan };
static void Main(string[] args)
{
Country country = new Country();
Console.WriteLine("Enter the number of country\n 1.Spain \n 2.The USA \n 3.Japan");
country = Console.ReadLine();
switch (country)
{
case Country.Spain:
Console.WriteLine("Its in Europe");
break;
case Country.USA:
Console.WriteLine("Its in North America");
break;
case Country.Japan:
Console.WriteLine("Its in Asia");
break;`enter code here`
}
Console.ReadKey();
}
}
You need to TryParse the string into Enum:
enum Country { Spain, USA, Japan };
static void Main(string[] args)
{
Country country;
Console.WriteLine("Enter the number of country\n 1.Spain \n 2.The USA \n 3.Japan");
string input = Console.ReadLine();
bool sucess = Enum.TryParse<Country>(input, out country);
if (!sucess)
{
Console.WriteLine("entry {0} is not a valid country", input);
return;
}
switch (country)
{
case Country.Spain:
Console.WriteLine("Its in Europe");
break;
case Country.USA:
Console.WriteLine("Its in North America");
break;
case Country.Japan:
Console.WriteLine("Its in Asia");
break;
}
Console.ReadKey();
}

Error in Switch case and not executing the program

The error is "Control cannot fall through from one case label ('case "B":')"
I am trying to do the following:
Upon starting the application a user will be prompted to login. The first action is to authenticate the user by validating an account exists for the entered username. Once the username has been matched to an account let the account object validate the entered pin (see Account class).
o After authentication, display a welcome message to the customer logged in using their name and display a menu offering options to get balance, deposit to account, withdraw from account, modify customer information, display current transactions, and exit.
static void Main(string[] args)
{
Account myCustAcc = new Account();
Transaction myCustTrans = new Transaction();
string input, choice = "";
string adminName, userName= "";
int adminPin, userPin;
//Login
Console.WriteLine("\t\t*****************WELCOME TO BANKING APPLICATION*********************\n");
choice = Console.Readline();
switch (choice)
{
case "A":
choice = "Admin";
Console.Write("\nAdminName :");
adminName = Console.ReadLine();
Console.Write("AdminName :");
Console.Write("AdminPIN :");
adminPin = Convert.ToInt32(Console.ReadLine());
//IT IS DEFINE USERNAME AND PASSWORD
if (adminName.Equals("admn1") && adminPin.Equals("9999"))
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Welcome to Bank");
}
break;
case "B":
{
choice = "User";
Console.Write("\nUserName :");
userName = Console.ReadLine();
Console.Write("UserName :");
Console.Write("PIN :");
userPin = Convert.ToInt32(Console.ReadLine());
//IT IS DEFINE USERNAME AND PASSWORD
if (userName.Equals("SMD") && userPin.Equals("1212"))
{
Console.ForegroundColor = ConsoleColor.White;
//Welcome Message with Name
Console.WriteLine("\t\t\t Welcome to Banking Application",userName);
Console.WriteLine("\n<<<Please Select Following Menus>>>");
do
{
//With Menu option to get balance, deposit/withdraw from account, modify customer information display current balance and exit
Console.WriteLine("\t1> GetBalance");
Console.WriteLine("\t2> Deposit");
Console.WriteLine("\t3> Withdraw");
Console.WriteLine("\t4> Modify");
Console.WriteLine("\t5> Display");
Console.WriteLine("\t6> Exit");
input = Console.ReadLine();
switch (input)
{
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
case "5":
break;
case "6":
default: Console.WriteLine("Exit the Application!!!");
break;
}
} while (input != "6");
}
break;
}
}
//Pause Display
Console.WriteLine("Press Any key to continue...........");
Console.ReadLine();
}
}
}
this is my account class
class Account
{
//Declare Instance Variables
private string customerFirstName;
private string customerLastName;
private string customerAddress;
private string customerState;
private int customerZip;
private double customerBalance;
//Class Variables
private static string customerUserName;
private static int customerPin;
//Retrieve Customer First Name
public string getCustomerFirstName()
{
return customerFirstName;
}
//Set Customer Name
public void setCustomerFirstName(String newFirstName)
{
customerFirstName = newFirstName;
}
//Retrieve Customer Last Name
public string getCustomerLastName()
{
return customerLastName;
}
//Set Customer Last Name
public void setCustomerLastName(String newLastName)
{
customerLastName = newLastName;
}
//Retrieve Customer Address
public string getCustomerAddress()
{
return customerAddress;
}
//Set Customer Address
public void setCustomerAddress(string newAddress)
{
customerAddress = newAddress;
}
//Retrieve Customer State
public string getCustomerState()
{
return customerState;
}
//Set Customer State
public void setCustomerZip(string newState)
{
customerState = newState;
}
//Retrieve Customer Zip
public int getCustomerZip()
{
return customerZip;
}
//Set Customer Zip
public void setCustomerZip(int newZip)
{
customerZip = newZip;
}
}
You need to move the break outside of the if statement. Also I recommend you to use brackes for case statements as they will make the intent clear(where statement block starts and ends).
Your code have too many execution path inside the single method, which makes code hard to read and hard to maintain. Refactor your code to methods which does only one thing, so that it will be easy to maintain.
Your main switch statement is using the choice variable which you are setting to an empty string and then never assigning. It looks like you meant to include a Console.Read after the initial message but forgot it.
The window flickers because 'choice' variable is not initialized to "A" or "B":
string input, choice = ""; //<----- here
Therefore there is no match for the switch block and the program quits.
Unreachable code warning is issued because you put some lines after the break command.
switch (choice)
{
case "A":
...
break;
case "B":
{
...
break; //<--- quits case "B", but the code below belongs to case "B"
}
//Pause Display
Console.WriteLine("Press the Enter key to Exit"); // <--- here is still considered part of case "B"
Console.ReadLine();
// case "B" ends here
} // end of outer switch block.
You may want to consider something like this:
...
Console.WriteLine("\t\t*****************WELCOME TO BANKING APPLICATION*********************\n");
Console.WriteLine("Choose A or B");
choice = Console.ReadLine();
switch (choice)
{
case "A":
...
break;
case "B":
...
break;
} // end of outer switch block.
//Pause Display
Console.WriteLine("Press the Enter key to Exit");
Console.ReadLine();

C#: Searching through arrays

I have a dvd app that stores dvds and blu-rays, I want to search the arrays by director. Below is the code for the inventory class I have seen many different ways to do this. There seems to be some debate as the best/most efficient way to accomplish this, any suggestions?
Blockquote
namespace MovieInventoryApplication
{
class Inventory
{
public Bluray[] BlurayMovies;
public DVD[] DVDMovies;
private int blurayCount;
private int dvdCount;
public Inventory()
{
BlurayMovies = new Bluray[5];
DVDMovies = new DVD[5];
blurayCount = 0;
dvdCount = 0;
}
public void AddBluray()
{
String strTitle;
int intReleaseYear;
int intRunningTimeMinutes;
String strDirector;
int intPrice;
int intRegionCode;
try
{
Console.Write("Enter a title: ");
strTitle = Console.ReadLine();
Console.Write("Enter a release year: ");
intReleaseYear = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the running time in minutes: ");
intRunningTimeMinutes = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the directors name: ");
strDirector = Console.ReadLine();
Console.Write("Enter a rental price: ");
intPrice = Convert.ToInt32(Console.ReadLine());
BlurayMovies[blurayCount] = new Bluray(strTitle, intReleaseYear, intRunningTimeMinutes, strDirector, intPrice);
blurayCount++;
Console.Write("Enter the DVD region code: ");
intRegionCode = Convert.ToInt32(Console.ReadLine());
DVDMovies[dvdCount] = new DVD(strTitle, intReleaseYear, intRunningTimeMinutes, strDirector, intPrice, intRegionCode);
dvdCount++;
}
catch (FormatException FormatException)
{
Console.WriteLine(FormatException.Message);
Console.WriteLine("Please enter a number in this field.");
}
}
public void AddDVD()
{
String strTitle;
int intReleaseYear;
int intRunningTimeMinutes;
String strDirector;
int intPrice;
int intRegionCode;
try
{
Console.Write("Enter a title: ");
strTitle = Console.ReadLine();
Console.Write("Enter a release year: ");
intReleaseYear = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the running time in minutes: ");
intRunningTimeMinutes = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the directors name: ");
strDirector = Console.ReadLine();
Console.Write("Enter a rental price: ");
intPrice = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the region code: ");
intRegionCode = Convert.ToInt32(Console.ReadLine());
DVDMovies[dvdCount] = new DVD(strTitle, intReleaseYear, intRunningTimeMinutes, strDirector, intPrice, intRegionCode);
dvdCount++;
}
catch (FormatException FormatException)
{
Console.WriteLine(FormatException.Message);
Console.WriteLine("Please enter a number in this field.");
}
}
public void ListAllBluray()
{
int position = 0;
while (BlurayMovies[position] != null)
{
Console.WriteLine(position + " " + BlurayMovies[position].strTitle);
position++;
}
}
public void ListAllDVD()
{
int position = 0;
while (DVDMovies[position] != null)
{
//position + 1 + " " +
Console.WriteLine(position + " " + DVDMovies[position].strTitle);
position++;
}
}
public void BlurayInfo(int position)
{
Console.WriteLine("Title: {0}", DVDMovies[position].strTitle);
Console.WriteLine("Release Year: {0}", DVDMovies[position].intReleaseYear);
Console.WriteLine("Running Time (Minutes): {0}", DVDMovies[position].intRunningTimeMinutes);
Console.WriteLine("Director: {0}", DVDMovies[position].strDirector);
Console.WriteLine("Price: {0}", DVDMovies[position].intPrice);
}
public void DVDInfo(int position)
{
Console.WriteLine("Title: {0}", DVDMovies[position].strTitle);
Console.WriteLine("Release Year: {0}", DVDMovies[position].intReleaseYear);
Console.WriteLine("Running Time (Minutes): {0}", DVDMovies[position].intRunningTimeMinutes);
Console.WriteLine("Director: {0}", DVDMovies[position].strDirector);
Console.WriteLine("Price: {0}", DVDMovies[position].intPrice);
Console.WriteLine("Region Code: {0}", DVDMovies[position].intRegionCode);
}
}
}
I think you have a flaw in the design.
The DVD and BluRay classes really should be either:
A single class with a Type property, probably an enum that would contain DVD and BluRay. This way, in several years once you get a new media, you can just add a value to the Enum and your application will be up to date.
Two different classes that implement a custom interface that you could call, say, IMedia.
Also, I highly suggest you take advantage of the List object in C# instead of arrays. It's very fast and you can add/remove items easily without having to resize your array.
Here's a lesson on Linq: http://www.functionx.com/csharp/linq/Lesson09.htm
Here's how I would create the Media class:
public class Media
{
public enum MediaType
{
DVD,
Bluray
}
public MediaType TypeOfMedia { get; set; }
public string Director { get; set; }
public string Title { get; set; }
public Media(string Title, string Director, MediaType TypeOfMedia)
{
this.TypeOfMedia = TypeOfMedia;
this.Director = Director;
this.Title = Title;
}
}
And here's an example how to use it:
List<Media> data = new List<Media>();
results.Add(new Media("Movie 1", "John D", Media.MediaType.DVD));
results.Add(new Media("Movie 2", "John D", Media.MediaType.DVD));
results.Add(new Media("Movie 3", "SomeOtherDirector", Media.MediaType.Bluray));
results.Add(new Media("Movie 4", "John D", Media.MediaType.Bluray));
IEnumerable<Media> listDirectors = from media in data
where media.Director == "John D"
select media;
foreach (Media media in listDirectors)
Console.WriteLine(media.Title);
Another example, your "List DVD" and "List Bluray" functions could really be a single function:
private void ListMediaByType(List<Media> data, Media.MediaType type)
{
foreach (Media media in data.Where(media => media.TypeOfMedia == type))
Console.WriteLine(media.Title);
}
As you see, these techniques simplifies querying by a LOT. :)
The most easies (imho) is using Linq:
string director = "Alfred Hitchcock";
IEnumerable<DVD> dvds = DVDMovies.Where(dvd => dvd.Director == director);
IEnumerable<DVD> blueRays = BlurayMovies.Where(br => br.Director == director);
List<DVD> allMatches = new List<DVD>();
allMatches.AddRange(dvds.Concat(blueRays));

Categories