Trying to create a switch-case menu - c#

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

Related

Unity - playerprefs deletes info

I'm making a game. it has a login panel and rememmer me button. i keep the info on regedit. when I click rememmer me button it works and when I start game after click button it gets my info like id and pass but when I start again it deletes my id and pass on regedit. So it get just one time. I couldn't find the problem or fix way. Can you help me? Thank you.
Here is my codes:
void Start()
{
if(PlayerPrefs.GetInt("BeniHatirla")==1)
{
Debug.Log("start "+PlayerPrefs.GetInt("BeniHatirla"));
BeniHatirlaGetir();
}
}
Here is the method ı called in start:
public void BeniHatirlaGetir()
{
isim = PlayerPrefs.GetString("BeniHatirlaIsim");
sifre = PlayerPrefs.GetString("BeniHatirlaSifre");
Debug.Log("kullanici "+isim+sifre);
BeniHatirlaUniSlider.value = 1;
Debug.Log("Ogrenm Durumu"+PlayerPrefs.GetInt("OgrenimDurumuBelirleme"));
switch (PlayerPrefs.GetInt("OgrenimDurumuBelirleme"))
{
case 1:
OrtaOkulKadiTextBox.text = isim.ToString();
OrtaokulKsifreTextBox.text = sifre.ToString();
LoginPanelleri[0].SetActive(true);
break;
case 2:
LiseKadiTextBox.text = isim.ToString();
LiseKsifreTextBox.text = sifre.ToString();
LoginPanelleri[1].SetActive(true);
break;
case 3:
UniversiteKadiTextBox.text = isim.ToString();
UniversiteKsifreTextBox.text = sifre.ToString();
LoginPanelleri[2].SetActive(true);
break;
}
}
And here is the rememmer me button:
public void BeniHatırlaButon()
{
PlayerPrefs.SetInt("BeniHatirla", 1);
switch (PlayerPrefs.GetInt("OgrenimDurumuBelirleme"))
{
case 1:
PlayerPrefs.SetString("BeniHatirlaIsim", OrtaOkulKadiTextBox.text.ToString());
PlayerPrefs.SetString("BeniHatirlaSifre", OrtaokulKsifreTextBox.text.ToString());
break;
case 2:
PlayerPrefs.SetString("BeniHatirlaIsim", LiseKadiTextBox.text.ToString());
PlayerPrefs.SetString("BeniHatirlaSifre", LiseKsifreTextBox.text.ToString());
break;
case 3:
PlayerPrefs.SetString("BeniHatirlaIsim", UniversiteKadiTextBox.text.ToString());
PlayerPrefs.SetString("BeniHatirlaSifre", UniversiteKsifreTextBox.text.ToString());
break;
}
}
If you're running some debugger, it may be missing out on when it actually saves the values to disk. From the documentation for PlayerPrefs:
By default Unity writes preferences to disk during OnApplicationQuit(). In cases when the game crashes or otherwise prematuraly exits, you might want to write the PlayerPrefs at sensible 'checkpoints' in your game. This function will write to disk potentially causing a small hiccup, therefore it is not recommended to call during actual gameplay.
So if you are exiting the application prematurely through debugging it may be that you just need to call PlayerPrefs.Save() right after you try to write the values.

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.

breaking out a loop in c#

I am having trouble figuring out how to break out of a loop that contains a switch statement.
i need to press 0 twice to exit the console why?
how can i fix it to exit from the first time
public void Start()
{
int choice = 0;
bool trueNumber = false;
do
{
ShowMenu(); // display the menu
Console.Write("Your Choice : ");
trueNumber = int.TryParse(Console.ReadLine(), out choice);
if (!trueNumber)
Console.WriteLine("Your Choice must be an integer. Try again.");
switch (choice) // select the relevant function based on user input
{
case 1:
CalculateCelsiusToFahrenheit();
break;
case 2:
CalculateFahrenheitToCelsius();
break;
case 0:
return; // exit when i press 0
default:
Console.WriteLine("Invalid Option: Choose 0, 1, or 2 Thank you ");
break;
}
} while (choice != 0);
}
If you are running this from an IDE (like Visual Studio), the default behavior for console applications is to end with a "Press any key to continue." so it waits with the output displayed.
related answer: VS setting

Variables in C# [duplicate]

This question already has answers here:
Use a variable from another method in C#
(2 answers)
Closed 2 years ago.
I've been searching for answers to solve this tiny bit of code, but without luck. I figure I have to declare the variable for "item" outside the method, but I can't seem to find a way to do so.
beginner
namespace Items
{
class Program
{
static void Main(string[] args)
{
bool myBool = true;
while (myBool)
{
Console.WriteLine("Welcome");
Console.WriteLine("[1] - add item");
Console.WriteLine("[2] - see content");
Console.WriteLine("[3] - erase content");
Console.WriteLine("[4] - close");
int input = Convert.ToInt32(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("add item");
var item = (Console.ReadLine());
Console.WriteLine("you just added: " + item);
break;
case 2:
Console.WriteLine("items added: " + items);
break;
case 3:
myBool = false;
break;
}
}
}
}
}
welcome to Stack Overflow! It's not quite clear what you're asking here - questions should typically include what you expect the code to do, and what it actually does. That said, I think I can see what you're going for. I've updated the code, and added some comments to describe the changes.
using System;
using System.Collections.Generic; // This namespace contains the 'List<>' class
namespace Items
{
class Program
{
static void Main(string[] args)
{
// I've moved this outside of the loop - I assume users would want the help message
// displayed on startup, not every single time they do something.
Console.WriteLine("Welcome");
Console.WriteLine("[1] - add item");
Console.WriteLine("[2] - see content");
Console.WriteLine("[3] - erase content");
Console.WriteLine("[4] - close");
// The list of items is created here, outside of the main loop.
var items = new List<string>();
// You don't need to declare a variable 'myBool' here
// We can just loop until the user exits the whole program
while (true)
{
int input = Convert.ToInt32(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("add item");
var newItem = Console.ReadLine();
Console.WriteLine("you just added: " + newItem);
break;
case 2:
Console.WriteLine("items added:");
foreach (var item in items)
Console.WriteLine(item);
break;
case 3:
items.Clear();
break;
case 4:
return;
}
}
}
}
}
I would recommend following some tutorials first, so you get an idea of variable scope - how long a variable lives for and where it can be accessed from.
It depends what you're trying to do here. On line 33, do you want to show all the items, or just the previous item to be added?
The error you're getting is that the variable "items" doesn't exist. If you just want to show the previous item to be added, then you can replace the word "items" with "item", and move the line where you declare "item" to outside the switch statement, to look like this:
static void Main(string[] args)
{
bool myBool = true;
var item;
while (myBool)
{
Console.WriteLine("Welcome");
Console.WriteLine("[1] - add item");
Console.WriteLine("[2] - see content");
Console.WriteLine("[3] - erase content");
Console.WriteLine("[4] - close");
int input = Convert.ToInt32(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("add item");
item = (Console.ReadLine());
Console.WriteLine("you just added: " + item);
break;
case 2:
Console.WriteLine("items added: " + item);
break;
case 3:
myBool = false;
break;
}
Now, we're declaring the variable item in the Main method rather than in the switch statement. Before, when you were declaring it in the switch statement, it was being reset every time you restarted the loop. Now, when the user changes it by inputting a value, it will be saved when you go back to the start of the loop, and so if the user inputs "2", they will be shown the last item they inputted.
If you want the user to be shown every item they have inputted, you'll need to use an array or collection.

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

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.

Categories

Resources