Avoid goto statement in C# - c#

I don't want to use some sort of goto statement, but I want the user to return to the main menu when the default case is executed. How?? I know this is a simple problem, but there must be lots of newbie who come across something very similar.
static void buycoffee()
{
Double price = 0;
int x = 0;
while (x == 0)
{
Console.WriteLine("Pick a coffee Size");
Console.WriteLine("1: Small");
Console.WriteLine("2: Medium");
Console.WriteLine("3: Large");
int Size = int.Parse(Console.ReadLine());
switch (Size)
{
case 1:
price += 1.20;
break;
case 2:
price += 1.70;
break;
case 3:
price += 2.10;
break;
default:
Console.WriteLine("This option does not exist");
///how to return to the main menu here
break;
}
Console.WriteLine("Would you like to buy more coffee?");
String Response = Console.ReadLine().ToUpper();
if (Response.StartsWith("Y"))
{
Console.Clear();
}
else
{
x += 1;
}
}
Console.WriteLine("The total bill comes to £{0}", price.ToString("0.00"));
}
}

replace your commented line with: continue;

As Nico Schertier said, you can accomplish this with something like the following:
int Size = -1;
while (Size == -1) {
Console.WriteLine("Pick a coffee Size");
Console.WriteLine("1: Small");
Console.WriteLine("2: Medium");
Console.WriteLine("3: Large");
Size = int.Parse(Console.ReadLine());
switch (Size)
{
case 1:
price += 1.20;
break;
case 2:
price += 1.70;
break;
case 3:
price += 2.10;
break;
default:
Size = -1;
Console.WriteLine("This option does not exist");
break;
}
}

Beside #Abion47 and #Dogu Arslan's answers you can also create a function for your menu and also one for your switch.
In this example it will create an infinite loop menu
static void Menu()
{
Console.WriteLine("Menu");
Console.WriteLine("1) Take me to My fancy menu");
}
static void SwitchFunc(string input)
{
switch (input)
{
case "1":
Menu();
string inputB = Console.ReadLine();
SwitchFunc(inputB);
break;
}
}
static void Main(string[] args)
{
Menu();
string input = Console.ReadLine();
SwitchFunc(input);
}

Related

How to go to main menu from submenu in c# console app

I have below menu options in my c# console app.
Menu
When user selects option 2 then user can see products in pagination format. I need to go to main menu again once user enter 0. I am not sure how can I do that as its console app. Once user done with products pagination thing, he should able to return to maain menu. There I am stuck.
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var shouldRun = true;
DisplayOptions();
while (shouldRun )
{
Console.Write("Enter an option: ");
var input = Console.ReadKey();
Console.WriteLine("\n");
ConsoleKeyInfo selectedCurrency ;
var currencyName = "USD";
switch (input.Key)
{
case ConsoleKey.NumPad1:
case ConsoleKey.D1:
Console.WriteLine("Printing all products");
OutputAllProduct(currencyName);
break;
case ConsoleKey.NumPad2:
case ConsoleKey.D2:
Console.WriteLine("Printing paginated products");
PaginatedProducts();
break;
case ConsoleKey.Q:
shouldRun = false;
break;
default:
Console.WriteLine("Invalid option!");
break;
}
Console.WriteLine();
DisplayOptions();
}
Console.Write("\n\rPress any key to exit!");
Console.ReadKey();
await _host.StopAsync(stoppingToken);
}
public void OutputPaginatedProducts()
{
int totalPages = products.Count() / 5;
do
{
Console.Write($"Please Enter Page number from 1 to {totalPages} or press 0 to exit\n");
int pageNumber;
if (int.TryParse(Console.ReadLine(), out pageNumber))
{
if (pageNumber >= 1 && pageNumber <= totalPages)
{
IEnumerable<Product> result = products.Skip((pageNumber - 1) * 5).Take(5);
Console.WriteLine();
Console.WriteLine("Displaying page: " + pageNumber);
foreach (Product product in result)
{
Console.WriteLine($"ID : {product.Id}\t Product Name : {product.ProductName}\tPrice : {product.Price} \tCurrency : {product.Price} {Currency.USD}");
}
Console.WriteLine();
}
else if(pageNumber==0)
{
Environment.Exit(0);
}
}
else
{
Console.WriteLine($"Page number must be integer between 1 and {totalPages}");
}
} while (1==1);
}
Just let the method return.
Instead of calling Environment.Exit(0);
You need to put a break or return there

How to use loops instead of goto statement

I'm new to C# and want to implement loops , right now I'm using goto statement and labels but I have read that it is not suggested to use goto statement
so i was thinking to implement loops instead of goto and labels , byt i dont know how can i replace goto with loops
and if possible please also give a small explanation of the answer
here is my code with goto and labels
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
int TotalCoffeeCost = 0;
// Start is a lable to point to this location so i can use it in goto
Start:
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
TotalCoffeeCost += 2;
break;
case 2:
TotalCoffeeCost += 5;
break;
case 3:
TotalCoffeeCost += 7;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a vaild choice");
goto Start;
}
// YesOrNo is a lable to point to this location so i can use it in goto
YesOrNo:
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
goto Start;
}else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
goto LastConfirmation;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a vailed choice");
goto YesOrNo;
}
// LastConfirmation is a lable to point to this location so i can use it in goto
LastConfirmation:
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if(UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
goto Amount;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
goto Start;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a vaild choice");
goto LastConfirmation;
}
// Amount is a lable to point to this location so i can use it in goto
Amount:
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if(EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
goto Amount;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}
}
Just use while loops and methods to make this work.
Your Start method could look like this:
public void Start(int TotalCoffeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, - large");
Console.Write(" ");
int CoffeChoice = 0;
do
{
CoffeChoice = int.Parse(Console.ReadLine());//Asking for Choice until you put in 1,2 or 3
}while(CoffeChoice != 1 | CoffeChoice != 2 | CoffeChoice != 3)
switch (CoffeeChoice)
{
case 1:
TotalCoffeeCost += 2;
break;
case 2:
TotalCoffeeCost += 5;
break;
case 3:
TotalCoffeeCost += 7;
break;
}
}
And you can call the method like this:
public static void Main()
{
int TotalCoffeeCost = 0;
Start(TotalCoffeCost);
}
We can use methods and a simple bool "lock" that either keeps you inside the while loop, or breaks out of it when conditions are met:
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
var exiting = false;
while (!exiting)
{
programLoop();
}
}
private int askForCoffee()
{
int totalCoffeeCost = 0;
bool invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
totalCoffeeCost += 2;
invalidChoice = false;
break;
case 2:
totalCoffeeCost += 5;
invalidChoice = false;
break;
case 3:
totalCoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
return totalCoffeeCost;
}
private void programLoop()
{
int TotalCoffeeCost = 0;
TotalCoffeeCost += askForCoffee();
var invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
TotalCoffeeCost += askForCoffee(); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
invalidChoice = false;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if(UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if(EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
}
else
{
invalidChoice = false;
}
}
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}

How to get variable totalCredit to increment properly

In my program, I am supposed to have the user enter course selections, up to a max of 3. The problem I am running into is that in order for the switch to end at 3 courses, it has to update the value of totalCredit until it reaches 9 (which is a total of 3 courses worth 3 credits each). Basically, when you've already entered 3 courses and you try to enter a 4th, it should spit out case -3 from within the WritePrompt method, but it appears to not be changing the totalCredit variable at all.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleRegisterStudent
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
}
void run()
{
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
string yesOrNo = "";
System.Console.WriteLine("Teacher's Copy");
do
{
WritePrompt();
choice = Convert.ToInt32(Console.ReadLine());
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit))
{
case -1:
Console.WriteLine("Your entered selection {0} is not a recognized course.", choice);
break;
case -2:
Console.WriteLine("You have already registerd for this {0} course.", ChoiceToCourse(choice));
break;
case -3:
Console.WriteLine("You can not register for more than 9 credit hours.");
break;
case -4:
Console.WriteLine("Registration Confirmed for course {0}.", ChoiceToCourse(choice));
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
Console.Write("\nDo you want to try again? (Y|N)? : ");
yesOrNo = (Console.ReadLine()).ToUpper();
} while (yesOrNo == "Y");
Console.WriteLine("Thank you for registering with us");
}
void WritePrompt()
{
Console.WriteLine("Please select a course for which you want to register by typing the number inside []");
Console.WriteLine("[1]IT 145\n[2]IT 200\n[3]IT 201\n[4]IT 270\n[5]IT 315\n[6]IT 328\n[7]IT 330");
Console.Write("Enter your choice : ");
}
int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit)
{
if (choice < 1 || choice > 7)
return -1;
else if (choice == firstChoice && choice == secondChoice && choice == thirdChoice)
return -2;
else if (totalCredit > 9)
return -3;
return -4;
}
void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice)
{
if (secondChoice == 0)
Console.WriteLine("You are currently registered for {0}", ChoiceToCourse(firstChoice));
else if (thirdChoice == 0)
Console.WriteLine("You are currently registered for {0}, {1}", ChoiceToCourse(firstChoice), ChoiceToCourse(secondChoice));
else
Console.WriteLine("You are currently registered for {0}, {1}, {2}", ChoiceToCourse(firstChoice), ChoiceToCourse(secondChoice), ChoiceToCourse(thirdChoice));
}
string ChoiceToCourse(int choice)
{
string course = "";
switch (choice)
{
case 1:
course = "IT 145";
break;
case 2:
course = "IT 200";
break;
case 3:
course = "IT 201";
break;
case 4:
course = "IT 270";
break;
case 5:
course = "IT 315";
break;
case 6:
course = "IT 328";
break;
case 7:
course = "IT 330";
break;
default:
break;
}
return course;
}
}
}
No error messages, no build errors, it's the just program logic that isn't working.
When you've successfully entered 3 courses, totalCredit gets incremented by 3 for 3 times. Given its initial value of 0, the value of totalCredit while processing the 4th course entry would be 9
If you want to trigger the -3, you need to change:
else if (totalCredit > 9)
to:
else if (totalCredit >= 9)

How do I create a terminable while loop in console application?

I am currently looking for a solution for this c# console application function
I tried searching for a method for creating a while loop that can terminate for the code below but I only came up with results relating to breaking while loops or the solution to be not to put it in a while loop
int P1Choice = int.Parse(Console.ReadLine());
while (true)
{
if (P1Choice == 1)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 1");
break;
}
if (P1Choice == 2)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 2");
break;
}
if (P1Choice == 3)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 3");
break;
}
if (P1Choice == 4)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 4");
break;
}
else
{
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
int P1Choice = int.Parse(Console.ReadLine());
}
}
I understand that I can't declare the local parameter "P1Choice" in this scope, but then are there any other methods to achieve the output of the code in such that when the user doesn't input the corresponding choices, that it loops again?
If you want to exit a while loop only when certain statements are met, then that's what you should state when entering your loop.
I would use a boolean to know whether the user made a right choice or not.
bool right_choice = false;
int P1Choice = int.Parse(Console.ReadLine());
while(!right_choice) {
switch(P1Choice) {
case 1:
right_choice = true;
{case 1 code};
break;
case 2:
right_choice = true;
{case 2 code};
break;
case 3:
right_choice = true;
{case 3 code};
break;
case 4:
right_choice = true;
{case 4 code};
break;
default:
break;
}
if (!right_choice) {
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
P1Choice = int.Parse(Console.ReadLine());
}
}
}
This way as soon as the user makes a correct choice you exit the loop.
Note that I changed your code to use a switch case instead of 4 ifs, since this would be the accepted way of implementing user input choice.
Good luck!
You just have to use readline inside your while loop and in else also do break. It should work this way:
int P1Choice;
while (true)
{
P1Choice = int.Parse(Console.ReadLine());
if (P1Choice == 1)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 1");
break;
}
if (P1Choice == 2)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 2");
break;
}
if (P1Choice == 3)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 3");
break;
}
if (P1Choice == 4)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 4");
break;
}
else
{
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
break;
}
}
I hope this is what you need. The possibles values are in the List "list" and it loops until the answer is one of the possible values:
int value = 0;
List<int> list = new List<int> { 1, 2, 3, 4 }; // choices are in the list
while (true)
{
Console.WriteLine("Please enter a number :");
if (int.TryParse(Console.ReadLine(), out value))
{
if (list.Contains(value))
break;
}
}
// value is in the list, deal with it.
One option can be to create method and keep calling until valid input comes:
public static void ProcessInput(string input)
{
int choice = Convert.ToInt32(input);
switch (choice)
{
case 1:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 1");
break;
case 2:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 2");
break;
case 3:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 3");
break;
case 4:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 4");
break;
default:
Console.WriteLine("");
Console.WriteLine("Input Invalid, Please press the number from the corresponding choices to try again");
ProcessInput(Console.ReadLine());
break;
}
and in your main program:
public static void Main()
{
Console.WriteLine("Hello World");
ProcessInput(Console.ReadKey());
}
You can do the following
var options = new Dictionary<int, Action> {
{1, () => {
//opt 1 code
}},
{2, () => {
//opt 2 code
}},
{3, () => {
//opt 3 code
}},
{4, () => {
//opt 4 code
}}
};
Console.WriteLine("Please enter you choice:");
int P1Choice;
while (!(int.TryParse(Console.ReadLine(), out P1Choice) && options.ContainsKey(P1Choice)))
{
Console.WriteLine("Input Invalid, Please press the number from the corresponding choices to try again:");
}
options[P1Choice]();
Here is code based on the post you deleted :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
BattleGrid grid = new BattleGrid();
grid.PrintGrid();
Console.ReadLine();
}
}
public class BattleGrid
{
public List<List<BattleGridCell>> grid = new List<List<BattleGridCell>>();
public BattleGrid()
{
for (int row = 0; row < 4; row++)
{
List<BattleGridCell> newRow = new List<BattleGridCell>();
grid.Add(newRow);
for (int col = 0; col < 4; col++)
{
BattleGridCell newCell = new BattleGridCell();
newRow.Add(newCell);
newCell.rowLetter = ((char)((int)'A' + row)).ToString();
newCell.colnumber = col.ToString();
}
}
}
public void PrintGrid()
{
foreach (List<BattleGridCell> row in grid)
{
Console.WriteLine("|" + string.Join("|", row.Select(x => "X" + x.rowLetter + x.colnumber)));
}
}
}
public class BattleGridCell
{
public string rowLetter { get; set; }
public string colnumber { get; set; }
}
}
You have 2 problems:
1. Your code doesn't compile because you try to bind P1Choice twice.
2. You ask for input twice in your else case.
To fix 1., you have to remove int from the second occurrence of P1Choice, the one in the else case.
To fix 2., you have to remove Console.readKey() in the else case.
Besides, your code will be easier to read if you use else if clauses instead of just if clauses.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
if (P1Choice == 1) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 1");
} else if (P1Choice == 2) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 2");
} else if (P1Choice == 3) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 3");
} else if (P1Choice == 4) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 4");
} else {
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}
Furthermore, I'd recommend you to use a switch clause instead of this many if clauses. But let that be a lecture for another day. :)
You can make further improvements.
In all cases, you call Console.WriteLine("") so move it outside.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
Console.WriteLine("");
if (P1Choice == 1) {
CenterWrite("You have chosen Default Empire 1");
} else if (P1Choice == 2) {
CenterWrite("You have chosen Default Empire 2");
} else if (P1Choice == 3) {
CenterWrite("You have chosen Default Empire 3");
} else if (P1Choice == 4) {
CenterWrite("You have chosen Default Empire 4");
} else {
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}
Instead of having fixed Strings, you can concatenate the value of P1Choice.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
Console.WriteLine("");
if (1 <= P1Choice && P1Choice <= 4) {
CenterWrite("You have chosen Default Empire " + P1Choice);
} else {
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}

How can I loop a case switch statement if an invalid value is chosen i.e the default

Here is an example where a menu of values is available. i would like to have it loop back to the start if none of the options are chosen.
static void Main(string[] args)
{
Console.WriteLine("1 : Option 1");
Console.WriteLine("2 : Option 2");
Console.WriteLine("3 : Option 3");
Console.WriteLine("4 : Option 4");
Console.WriteLine("5 : Option 5");
Console.Write("Please enter your option choice: ");
string choice = Console.ReadLine();
int intChoice = int.Parse(choice);
switch (intChoice)
{
case 1:
Console.WriteLine("you chose 1");
break;
case 2:
Console.WriteLine("you chose 2");
break;
case 3:
Console.WriteLine("you chose 3");
break;
case 4:
Console.WriteLine("you chose 4");
break;
case 5:
Console.WriteLine("you chose 5");
break;
}
}
I've tried to do it through using classes and method, but i just got really confused.
thank you in advance for any help.
Wrap the whole thing in a do-while block:
bool isValid = true;
do
{
isValid = true;
// Write to console
// read from console
switch(intChoice)
{
// Place some cases here.
default:
Console.WriteLine("Invalid Choice")
isValid = false;
}
}
while(!isValid);
Use a boolean value as a flipswitch that tell the while loop to continue running or not. Here's a small example:
bool stillRunning = true;
while (stillRunning)
{
Console.WriteLine("Enter a number.");
string input = Console.ReadLine();
int key = Convert.ToInt32(input);
switch (key)
{
case 1:
// Do something.
stillRunning = false;
break;
case 2:
// Do something.
stillRunning = false;
break;
default:
Console.WriteLine("No key selected.");
break;
}
}
you can use default
switch (intChoice)
{
case 1:
Console.WriteLine("you chose 1");
break;
case 2:
Console.WriteLine("you chose 2");
break;
.......
default:
//your logic here
break;
}
it is your choice after that how you like to do it. you can use a while and a Boolean value like this:
static void Main(string[] args)
{
Console.WriteLine("1 : Option 1");
Console.WriteLine("2 : Option 2");
Console.WriteLine("3 : Option 3");
Console.WriteLine("4 : Option 4");
Console.WriteLine("5 : Option 5");
Console.Write("Please enter your option choice: ");
bool correct = true;
while (correct)
{
string choice = Console.ReadLine();
int intChoice = int.Parse(choice);
switch (intChoice)
{
case 1:
Console.WriteLine("you chose 1");
break;
case 2:
Console.WriteLine("you chose 2");
break;
case 3:
Console.WriteLine("you chose 3");
break;
case 4:
Console.WriteLine("you chose 4");
break;
case 5:
Console.WriteLine("you chose 5");
break;
default:
correct = false;
break;
}
}
}
Thus you need only one number, it's better to use GetKey method, then reading string value from console and then parsing it to int:
DisplayOptions();
bool choiceDone;
do
{
choiceDone = true;
switch(GetChoice())
{
case ConsoleKey.D1:
Console.WriteLine("you chose 1");
break;
case ConsoleKey.D2:
Console.WriteLine("you chose 2");
break;
// etc
default:
choiceDone = false;
break;
}
} while(!choiceDone);
Also I have extracted several methods, to make code more clean:
private ConsoleKey GetChoice()
{
Console.Write("Please enter your option choice: ");
return Console.ReadKey().Key;
}
private void DisplayOptions()
{
Console.Clear();
Console.WriteLine("1 : Option 1");
Console.WriteLine("2 : Option 2");
Console.WriteLine("3 : Option 3");
Console.WriteLine("4 : Option 4");
Console.WriteLine("5 : Option 5");
}
public void GetInput()
{
int inputValue = 0;
bool isValidInput = false;
List<int> validEntries = new List<int> { 1,2,3, 42, 55, 69};
while (!isValidInput)
isValidInput = int.TryParse(Console.ReadLine(), out inputValue) && validEntries.Contains(inputValue);
switch (inputValue)
{
case 1:
{
// something
break;
}
case 2:
{
// something else
break;
}
default:
{
//yet something else
break;
}
}
}
Edit: Added explicit value check instead of accepting any integer.
The most obvious solution seems to be:
bool loop = true;
while (loop)
{
loop = false;
switch (Console.ReadLine())
{
case "1":
Console.WriteLine("you chose 1");
break;
case "2":
Console.WriteLine("you chose 2");
break;
case "3":
Console.WriteLine("you chose 3");
break;
case "4":
Console.WriteLine("you chose 4");
break;
case "5":
Console.WriteLine("you chose 5");
break;
default:
loop = true;
break;
}
}
There could be a better way to do this though.

Categories

Resources