C# How do I make a switch ignore invalid input? - c#

I am trying to make a simple console game that starts with a title screen. The user inputs 'N' for a new game, 'L' to load a game, or 'E' to exit. I have this set up as a switch, but I need to know how to make the program ignore any input other than the aforementioned keys. I've Googled this question but didn't find an answer. Please help if you can.
I don't see much point in posting the code as 10 lines of a simple switch probably wouldn't be terribly helpful to solving the problem. Also, if there would be an easier / more efficient way than a switch, I would love to know.
Thanks.

You can use a default: statement to handle the other (unknown) cases:
switch(inputString.ToLower())
{
case "n":
// Handle new
break;
//.. handle known cases
default:
Console.WriteLine("Unknown option chosen. Please enter valid option:");
// Re-read values, etc?
break;
}
Anything not specified in one of your other cases will fall into the default case, which you can then use to prompt for valid input.

If you want to actually ignore all keys other than valid ones you could do something like this:
public static char ReadKey(IEnumerable<char> validKeys)
{
var validKeySet = new HashSet<char>(validKeys);
while (true)
{
var key = Console.ReadKey(true);
if (validKeySet.Contains(key.KeyChar))
{
//you could print it out if you wanted.
//Console.Write(key.KeyChar);
return key.KeyChar;
}
else
{
//you could print an error message here if you wanted.
}
}
}
When you use ReadKey(true) the true indicated that it will intercept that key and not display it on the console. This gives you the option of determining if it's valid or invalid.

If a switch statement does not have a default block, and if the expression being switched on does not match any of the case blocks, the switch statement does nothing.

When you have only 3 cases, a switch isn't much more efficient than just a simple if-else construct.
if (input == "N")
{
// New game
}
else if (input == "L")
{
// Load game
}
else if (input == "E")
{
// Exit game
}
// if none of the cases match, the input is effectively ignored.
If you insist on using a switch, then your construct is very similar:
switch (input)
{
case "N":
//New Game
break;
case "L":
//Load Game
break;
case "E":
//Exit Game
break;
default:
//Do nothing (ignore unmatched inputs)
break;
}

Thanks for the replies, guys. I managed to solve the problem by doing the following:
static void titleInput()
{
ConsoleKeyInfo titleOption = Console.ReadKey(true);
switch (titleOption.Key)
{
case ConsoleKey.N:
Console.Clear();
break;
case ConsoleKey.L:
break;
case ConsoleKey.E:
Environment.Exit(0);
break;
default:
titleInput();
break;
}
}
I'm not sure how 'proper' this is, but it does what I need it to do. Any keys other than 'N', 'L', and 'E' no longer do anything.

Related

Exit program after pressing escape button C#

I need a way so user can exit the program by pressing escape button, so CancelKeyPress event doesn't work here. It is very important that the user can quit at any time they want.
I really have no idea how to do it as I am beginner, so I count on you. Thanks in advance.
What i do when i make a Console application is a switch statement for exit.
switch (choice)
{
case "1":
util.Option();
break;
.
.
.
case "q":
System.Environment.Exit(1);
default:
break;
}
System.Environment.Exit(1);can help you exit your console.
Based on your description, I think you have solved the following code:
static void Main(string[] args)
{
ConsoleKeyInfo CurrentInputKey;
while(true)
{
// Your Other Codes
Console.WriteLine("\rHello C# Developer.");
CurrentInputKey = Console.ReadKey();
if(CurrentInputKey != null && CurrentInputKey.Key == ConsoleKey.Escape)
{
Console.WriteLine("Exit ...");
System.Environment.Exit(0);
}
}
}

How do I add a Y/N to Switch-Cases in C#?

I'm a complete Newbie to the world of programming, yet I really wish to learn a lot as quick as possible and now came up to a problem that I can't find to solute just via researching and "learning- by doing" (Trying around).
Basically I'm trying to work on a small console- based TextAdventure in C Sharp (With VisualStudios) Now I came to a Case- Switch (Offering the User some Options to read and walk through), but I wish to add a Y/N Confirmation in case the User decides to take a different path. For now it's only for the starting point of the story:
Does the User want to go into "The Wilds", "The City", "The Farm". Something as simple as that just in addition: "Are you sure (Y/N)?" leading the No to return the given choices.
Thank you all in advance and stay healthy!
Menu mainMenu = new Menu(prompt, options);
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
private void TakeYourLeave()
{
WriteLine("\nYou are about to take your leave... Are you sure ? (Y/N)");
ReadKey();
Environment.Exit(0);
}
private void VisitTheMemorial()
{
Clear();
//FILLER//
WriteLine("You may proceed by the press of any button.");
ReadKey(true);
RunMainMenu();
}
private void EnterTheWorld()
{
string prompt = "Where would you like to start your journey?";
string[] options = { "The Slums", "The Wilds", "The City", "The Farm" };
Menu startMenu = new Menu(prompt, options);
int selectedIndex = startMenu.Run();
BackgroundColor = ConsoleColor.White;
switch (selectedIndex)
{
case 0:
ForegroundColor = ConsoleColor.Black;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 1:
ForegroundColor = ConsoleColor.Green;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 2:
ForegroundColor = ConsoleColor.Red;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 3:
ForegroundColor = ConsoleColor.Yellow;
WriteLine("\n ||Small Description|| Are you sure to take this path? (Y/N)");
break;
}
In this case, you need to take care of a few things:
Make sure that the entire switch-statement logic is in a while-loop, as such:
while (True) {
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
Check with your function if the input given is "No", if such, then immeditely return so your function exits before any navigation
private void VisitTheMemorial()
{
userInput = readKeyFunction();
if (userInput == "no") {
return;
}}
Finally, if the user doesn't select no, just do nothing and let the function go on
It is best to handle the 'Are you sure?' inside the menu.Run(), and return a value to the selectedIndex after the confirmation. Also avoid using while loop at the main flow in this case.
Note: you have to think in a modular way. Consider your Menu class as a module which handles user choice. The main flow does not have to bother about the confirmation by the user, it just have to process the final result of the user.
Another suggestion: Use enums instead of integers wherever possible for multiple choices.

Trying to create a switch-case menu

So I'm working on a Switch-Case menu for my program but I'm having multiple issues (I'm probably missing something real obvious here)
So first off I'm trying to implement a while loop to make it possible to return to the menu after executing any of the case methods. However when trying to implement a while loop it doesn't seem to recognise my bool variable for some reason.
Secondly I'm not quite sure how to make it so the user can return to the start menu after they've done what they want to do in the case they've chosen, this probably has a real easy solution, but I just can't find one.
[code]
private string[] säten = new string[24];
private int Antal_passagerare = 0;
public void Run()
{
bool continue = true;
while(continue)
{
string menu = (Console.ReadLine());
int tal = Convert.ToInt32(menu);
switch(tal)
{
case 1:
Add_passagerare;
break;
case 2:
break;
case 3:
break;
}
}
}
[/code]
Your problem is that your local variable name conflicts with the C# keyword (or statement) continue which controls the flow of a loop (e.g. for, foreach, while, etc). Another control flow keyword is break.
You must rename the local variable. But because of the flow control keywords you can drop the local variable (see below). Also use Int32.TryParse to avoid your program from crashing, if the user inputs a non numeric value. In this context you can see the statements continue and break at work:
// Start an infinite loop. Use the break statement to leave it.
while (true)
{
string userInput = Console.ReadLine();
// Quit if user pressed 'q' or 'Q'
if (userInput.Equals("Q", StringComparison.OrdinalIgnoreCase)
{
// Leave the infinite loop
break;
}
// Check if input is valid e.g. numeric.
// If not show message and ask for new input
if (!(int.TryParse(userInput, out int numericInput))
{
Console.WriteLine("Only numbers allowed. Press 'q' to exit.");
// Skip remaining loop and continue from the beginning (ask for input)
continue;
}
switch (numericInput)
{
case 1:
break;
case 2:
Add_passagerare();
break;
case 3:
break;
}
}

Console.ReadKey seems to be reading the wrong key?

I'm just starting out so I'm in the middle of writing my first console application from scratch. I have this line of code, when I hit d it correctly takes me to the next step and sets disadvantage to true, however if I hit a it executes the else statement for some reason. Any ideas what the cause is?
Console.WriteLine("Press the A key for advantage, or the D key for disadvantage");
var rollType = Console.ReadKey();
Console.WriteLine(System.Environment.NewLine);
if (rollType.Key == ConsoleKey.A)
{
advantage = true;
}
if (rollType.Key == ConsoleKey.D)
{
disadvantage = true;
}
else
{
Console.WriteLine("Invalid Input");
StartApp();
}
Just add make this small change! (Adding else in your second conditional)
if (rollType.Key == ConsoleKey.A)
{
advantage = true;
}
else if (rollType.Key == ConsoleKey.D)
{
disadvantage = true;
}
else
{
Console.WriteLine("Invalid Input");
StartApp();
}
What was happening before is your Console would read an A key and enter the first conditional. Since the second and third conditional was separate from the first, the second would also be checked and if not true (which in this case it would not be true) it would no matter what enter the else statement. Hope this helps.
Seems like the program is being executed exactly as you’ve written it to.
if (rollType.Key == ConsoleKey.A)
{
advantage = true;
} // First conditional check ends here
// This is another conditional block
if (rollType.Key == ConsoleKey.D)
{
disadvantage = true;
}
else // You pressed A, so this block is executed
{
Console.WriteLine("Invalid Input");
StartApp();
}
If you hit A, it will excude A and else part of D. After all, A equals A but A does not equal D.
What you want is propably a switch/case statement.
switch(rollType){
case ConsoleKey.A:
advantage = true;
break;
case ConsoleKey.D:
disadvantage = true;
break;
default:
Console.WriteLine("Invalid Input");
break;
}
switch/case statement and do/while loop - these two are the fundament of console programm flow.

Is there an easier way of writing several if/else statements into eachother?

I sometimes have myself writing code which requires several layers of if/else statements incorporated into each other (example can be found below).
I was wondering if I could shorten it up a bit, because sometimes I have trees of if/else statements of over 70 lines of code, and they are honestly just filling way too much compared to how many of the lines seem redundant.
Here's an example code:
if (labelGiveTip1.Visible == true)
{
if (labelGiveTip2.Visible == true)
{
labelGiveTip3.Visible = true;
if (labelGiveTip3.Visible == true)
{
Custom_DialogBox.Show("All of your hints for this assignment is used, do you want annother assignmment?", //main text argument
"Error: No more hints", //header argument
"Back", //first button text argument
"Get a new assignment"); //second button text argument
//this is a custom dialog box
result = Custom_DialogBox.result;
switch (result)
{
case DialogResult.Yes:
buttonNextAssignment.PerformClick();
break;
case DialogResult.Cancel:
break;
default:
break;
}
}
}
else
{
labelGiveTip2.Visible = true;
}
}
else
{
labelGiveTip1.Visible = true;
}
In my code I tend to check the false condition first and return ASAP. This approach has helped me over years to reduce deeply nested if else. Other than that try to separate related functionalities in to different methods. The example method provided crams too much of logic into one method. If you have ReSharper, it suggests nice improvements and over a period of time, it becomes a habit.
You may check the negated variant of the condition and use else if conditions to avoid that much nesting. E.g. a simplified version for your code:
if (!labelGiveTip1.Visible)
labelGiveTip1.Visible = true;
else if(!labelGiveTip2.Visible)
labelGiveTip2.Visible = true;
else
{
labelGiveTip3.Visible = true;
Custom_DialogBox.Show("All of your hints for this assignment is used, do you want annother assignmment?", //main text argument
"Error: No more hints", //header argument
"Back", //first button text argument
"Get a new assignment"); //second button text argument
//this is a custom dialog box
result = Custom_DialogBox.result;
switch (result)
{
case DialogResult.Yes:
{
buttonNextAssignment.PerformClick();
break;
}
case DialogResult.Cancel:
{
break;
}
default:
{
break;
}
}
}
It is also unnecessary to write labelGiveTip1.Visible == true or labelGiveTip1.Visible == false when they are already boolean values.

Categories

Resources