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
Related
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
(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();
I am currently writing a program where I have to
1) Giving user some options: 1.Search by name? 2. Search by date of birth?
2) If user selects search by name, ask them to put first name and then give the output
3) If user selects search by date of birth, ask them to put date of birth with format (MM/DD/YYYY) and then give the output.
I have to Repeat the options if the validation failed or couldn’t find the data.
I am struggling with the concept of repeating the options. ANy help is extremely appreciated.
My code so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Week2Tutorial
{
class Program
class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Lastname { get; set; }
public DateTime DOB { get; set; }
public string Gender { get; set; }
}
static void Main(string[] args)
{
var students = new List<Student>()
{
new Student() { Id = 1,FirstName = "Min Chul",Lastname = "Shin",DOB = new DateTime(2010,01,01),Gender = "Male"},
new Student() { Id = 2,FirstName = "Nicky", Lastname = "Lauren", DOB = new DateTime(2009, 01, 01), Gender = "Female"},
new Student() { Id = 3, FirstName = "Amy", Lastname = "Park", DOB = new DateTime(2008, 01, 01), Gender = "Female" },
new Student() { Id = 4, FirstName = "Aurelie", Lastname = "Adair", DOB = new DateTime(2007, 01, 01), Gender = "Female" }
};
//foreach (var x in students)
//{
// Console.WriteLine("Id = {0}, FirstName = {1}, Lastname = {2}, DOB = {3}, Gender = {4}",x.Id,x.FirstName,x.Lastname,x.DOB,x.Gender);
//}
Console.WriteLine(" Please Choose one of the options:");
Console.WriteLine("1> Search by first name");
Console.WriteLine("2> Search by date of birth");
switch ( Convert.ToInt32(Console.ReadLine()))
{
case 1:
Console.WriteLine("You choose:1");
Console.WriteLine("Type your first name:");
var a = Console.ReadLine();
var case1 = students.Where(x=>x.FirstName==a);
if (case1.Count()!=0)
{
Console.WriteLine("Found! Here are the details:");
foreach (var x in case1)
{
Console.WriteLine("Name: {0}{1} D.O.B:{2} and Gender{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
case 2:
Console.WriteLine("You choose:2");
Console.WriteLine("Enter your Date of Birth in format MM/DD/YYYY:");
var b = DateTime.Parse(Console.ReadLine());
//Console.WriteLine(b);
//Console.ReadLine();
var case2 = students.Where(x => x.DOB == b);
if (case2.Count() != 0)
{
Console.WriteLine("Found! Here are your details");
foreach (var x in case2)
{
Console.WriteLine("Name:{0} {1} DOB:{2} Gender:{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
default:
Console.WriteLine("Please enter the valid option");
break;
}
}
}
}
It can be Done be with do while loop here is the general syntax of do while Loop
do {
code to be executed;
} while (condition is true);
what is do while loop it is an endless loop that is executes the code till the condition is true.
In Your Case we are taking a new varibale temp which is intially zero means no
result if any of your switch case gets true and find results according to user's search query the count of that result will be copied to temp variable now temp no longer have zero value means condition is false means the code will not be executed again
You Just Need to start an endless loop till the condition is true
do{
var temp=0; ///Temporary variable to check the result count
//intially variable b will be zero because INtially result count is zero
Console.WriteLine(" Please Choose one of the options:");
Console.WriteLine("1> Search by first name");
Console.WriteLine("2> Search by date of birth");
switch ( Convert.ToInt32(Console.ReadLine()))
{
case 1:
Console.WriteLine("You choose:1");
Console.WriteLine("Type your first name:");
var a = Console.ReadLine();
var case1 = students.Where(x=>x.FirstName==a);
temp=case1.Count(); //Getting result count in another variable
if (case1.Count()!=0)
{
Console.WriteLine("Found! Here are the details:");
foreach (var x in case1)
{
Console.WriteLine("Name: {0}{1} D.O.B:{2} and Gender{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
case 2:
Console.WriteLine("You choose:2");
Console.WriteLine("Enter your Date of Birth in format MM/DD/YYYY:");
var b = DateTime.Parse(Console.ReadLine());
//Console.WriteLine(b);
//Console.ReadLine();
var case2 = students.Where(x => x.DOB == b);
temp=case2.Count(); //Getting result count in another variable
if (case2.Count() != 0)
{
Console.WriteLine("Found! Here are your details");
foreach (var x in case2)
{
Console.WriteLine("Name:{0} {1} DOB:{2} Gender:{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
default:
Console.WriteLine("Please enter the valid option");
break;
}
}while(temp==0); ////Endless Loop while result is zero
intially temp is equal to zero means result count is zero
so it will again intiate the loop However if there is any result
that means temp is not equal to zero it will not execute the code
Just use while loop.
Example from: https://www.dotnetperls.com/console-readline
using System;
class Program
{
static void Main()
{
while (true) // Loop indefinitely
{
Console.WriteLine("Enter input:"); // Prompt
string line = Console.ReadLine(); // Get string from user
if (line == "exit") // Check string
{
break;
}
Console.Write("You typed "); // Report output
Console.Write(line.Length);
Console.WriteLine(" character(s)");
}
}
}
So I want to make a list of names. I want this list to go on until user inputs 0 to quit, after user types 0 I want all names to be displayed. You probably see what I'm trying to do from the code below...that "typedName" is there just so you see what I'm trying to do.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
bool over = false;
while (over != true)
{
names.Add(Console.ReadLine());
if(typedName == "0")
{
over = true;
}
}
Console.WriteLine("Entered names : ");
names.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
}
First you need the typedName to be captured and then check if it is equal to 0.
if it is not add it to the list
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
while (true)
{
var typedName = Console.ReadLine();
if (typedName.Equals("0"))
{
break;
}
names.Add(typedName);
}
Console.WriteLine("Entered names : ");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
if(typedName == "0")
Well, what is typedName? Or what should it be? I suspect it should be the input entered by the user, something like this:
var typedName = Console.ReadLine();
You can then add it to the list by using that variable:
names.Add(typedName);
And compare it with "0" as you already do, etc.
your code is not complete that is why is not working...
you are missing the most important part:
populate the list if and only if typedName != "0"
while (!over)
{
var typedName =Console.ReadLine();
if(typedName == "0")
{
over = true;
}else
{
Console.WriteLine("Enter a name... ");
names.Add(Console.ReadLine());
}
...
}
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));