Using enums and switch c# [duplicate] - c#

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

Related

How do you execute a method only if another one has been run?

I have a choice for the user in Main using a switch. Depending on what the user chooses, several choices later, the program will either end or not. At least, that is what I'm trying to accomplish.
//This is in Main
string[] menyVal2 = new string[] {"Go to the hotel room", "Go to the dining hall"};
string title2 = "text";
int choice2 = menu(menuChoice2, title2);
switch (choice2)
{
case 0:
hotelRoom();
break;
case 1:
diningHall();
break;
}
Many lines of code later...
public static void save()
{
Console.Clear();
string[] menuChoice = {"Chapter 2", "Back to start"};
string title = "text";
int choice = menu(menuChoice, title);
switch (val)
{
case 0:
if (hotelRoom = true) //this if-statement does not work
{
withoutCross();
}
else if (diningHall = true)
{
withCross();
}
break;
case 1:
Main(new string[] { });
break;
}
}
When I understand your title of the question correctly, then this is a solution:
Make the return type of the method bool and fill it to a variable.
bool isMethodExecuted = MyMethod();
Later you can check with a if-Statement, if the method is executed:
if(isMethodExecuted)
MyOtherMethod();

How can I escape from this loop?

I am a beginner at coding - I just started a week ago. I am trying to develop a program where the user can either see all of the names in a list or add a name to a list. When the user prompts to see the names in the list, and then decides to take another action, they are stuck in an endless loop where they can only see the names again. I want them to be able to go back to the start and choose to either see the names or add a name.
I've tried reorganizing and looking things up, but I'm still at a loss.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> names = new List<string>();
names.Add("Vasti");
names.Add("Cameron");
names.Add("Ezra");
names.Add("Tilly");
bool program = false;
bool program2 = false;
Console.WriteLine("Welcome to the names lost! If you wish to add
a name to the list, type 1. If you want to see current names in
the list,
type 2.");
string userChoice = Console.ReadLine();
do
{
switch (userChoice)
{
case "1":
Console.WriteLine("Add a name to the squad.");
string userAddName = Console.ReadLine();
names.Add(userAddName);
break;
case "2":
Console.WriteLine("Here's the list:");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Wanna do that again? Type yes or
no.");
do
{
string userContinue = Console.ReadLine();
switch (userContinue)
{
case "yes":
program = true;
program2 = false;
break;
case "Yes":
program = true;
program2 = false;
break;
case "no":
program = false;
program2 = false;
break;
case "No":
program = false;
program2 = false;
break;
default:
Console.WriteLine("Please enter either
yes or no");
userContinue = Console.ReadLine();
program2 = true;
break;
}
}
while (program2 == true);
break;
default:
Console.WriteLine("Please type either 1 or 2 to
select an option.");
break;
}
}
while (program == true);
}
}
I expect the user to return to the beginning prompt, but they are stuck in the same prompt over and over. There are no error messages.
Two major things to cover your difficulties.
First, the input hint should be in the loop so it can show when each loop begin.
Second, do while loop decide if the loop should continue at the end and in your design; it depends on what user input which should be directly utilized as while condition.
Therefore, your code could be simplified as
public static void Main()
{
List<string> names = new List<string>() { "Vasti", "Cameron", "Ezra", "Tilly" };
string userChoice = "";
do
{
Console.WriteLine($#"Welcome to the names lost!{Environment.NewLine} If you wish to add a name to the list, type 1.{Environment.NewLine} If you want to see current names in the list, type 2.");
userChoice = Console.ReadLine();
switch (userChoice)
{
case "1":
Console.WriteLine("Add a name to the squad.");
string userAddName = Console.ReadLine();
names.Add(userAddName);
break;
case "2":
Console.WriteLine("Here's the list:");
foreach (string name in names)
{
Console.WriteLine(name);
}
break;
default:
Console.WriteLine("Please type either 1 or 2 to select an option.");
break;
}
Console.WriteLine(#"Wanna do that again? Type yes or no.");
userChoice = Console.ReadLine();
}
while (userChoice.Equals("yes", StringComparison.OrdinalIgnoreCase));
Console.WriteLine("Program finished");
Console.ReadLine();
}
Change the do{}while() loops to regular while(){} loops.Move string userChoice = Cosole.ReadLine(); inside of the top while loop or you will never ask for other options. . . Also set the ((bool program=true; and bool program=true;)) at the beginning. Do{}while() loops do everything inside the {} first then check to see if the while statement is still true.

How to repeat until the correct information is provided in c#?

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

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

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