I've made a switch-case where I use the up arrow key, down arrow key and enter key. However I can't think of how to put code into my enter case in which I can choose an option.
public static void entries()
{
keyPressed = Console.ReadKey(true);
switch (keyPressed.Key)
{
case ConsoleKey.DownArrow:
if (keyPressed.Key.ToString() == "DownArrow")// selects the curitem when the down arrow key is pressed
{
curItem++;
if (curItem > menuItems.Length - 1) curItem = 0;
}
break;
case ConsoleKey.UpArrow:
if (keyPressed.Key.ToString() == "UpArrow")// selects the curitem when the up arrow key is pressed
{
curItem--;
if (curItem < 0) curItem = Convert.ToInt16(menuItems.Length - 1);
}
break;
case ConsoleKey.Enter:
if (keyPressed.Key.ToString() == "Enter")// when enter is pressed it will go to one of the choices
{
}
break;
default:
break;
}
}
Your idea about nesting if statements is correct, or having another switch. I would probably re-factor this into another function though:
case ConsoleKey.Enter:
chooseOption(curItem);
break;
...
void chooseOption(int item)
{
switch(item)
{
case 1:
//Do item 1
break;
case 2:
//Do item 2
break;
case 3:
//Do item 3
break;
}
}
Based on your comment. here is how you can display the current item inside the menuItems array. I'm assuming menuItems holds some strings or ints or something that can be easily written to the console.
case ConsoleKey.Enter:
// when enter is pressed it will go to one of the choices
Console.Clear();
Console.WriteLine(menuItems[curItem]);
break;
Related
I have a console application in c# where I have to edit data inside a xml. This works so far I can get through id selection the dataset I want to edit and then edit single values. What I want to achieve is if the user gives an specific value after editing he/she should be able to go back a step back and edit other values of the same dataset.
For example: User edits the name of a customer with id 2 and wishes after saving the name to change adress. The application should be able to recognize the input from before and then just give the options of which the user can change the values again.
I tried calling the method inside the method but my application just finishes after saving the new value,
this is my code:
bool inputTester = true;
while (inputTester)
{
Console.WriteLine("Welche Seiner Daten möchten Sie verändern?");
Console.WriteLine("1) Für Vornamen");
Console.WriteLine("2) Für Nachnamen");
Console.WriteLine("3) für Adresse");
Console.WriteLine("4) für Geburtsdatum");
Console.WriteLine("5) für Bankdaten");
Console.WriteLine("Bitte geben Sie nun eine Option ein");
switch (Console.ReadLine())
{
case "1":
tgt = tempId;
var name = tgt.Descendants("firstName").FirstOrDefault();
Console.WriteLine("Bitte geben sie den neuen Vornamen ein");
name.Value = Console.ReadLine();
xDoc.Save(filepath);
Console.WriteLine("Kunde gespeichert");
Console.Clear();
Console.WriteLine("Möchten Sie weitere Daten dieses Kunden bearbeiten? Falls Ja drücken Sie 1");
if (Console.ReadLine().Equals(1))
break;
break;
I tried to do it in case 1 with calling the method inside it.
EDIT: I tried to do it with the while advices but still the outcome is the same. The program just finishes and then closes itself.
I reduced my code to the minimal state posible to try it localy. I hope this is fine like this.
Place the Switch Statement in a While(true) Loop and when you want to go back to the start of the loop use the:
Continue
statement, this will start the loop again.
And when you want to exit the loop just use:
Break
I will try to simplify your issue in order to illustrate the error you made.
The requirement is :
The program will ask for "1" or "2" and sum it till you give up and type "Stop".
Your attempt looked like this : It wont loop and only ask once.
static int Count_Original()
{
var num = 0;
Console.WriteLine("Original: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
return num;
case "2":
num += 2;
return num;
}
return num;
}
If we had a loop: It will still not loop as the return make us quit the method.
static int Count_Loop()
{
var num = 0;
while (true)
{
Console.WriteLine("Loop: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
return num;
case "2":
num += 2;
return num;
}
return num;
}
}
Simply removing the return won't fix it, we are now trap in the loop.
static int Count_Trap()
{
var num = 0;
while (true)
{
Console.WriteLine("Trap: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
break;
case "2":
num += 2;
break;
default: // I didn't understand the input. Let me ask again.
break;
}
};
return num; // Never reach
}
The final version will look like this:
A break out option using return
a default in case we didn't type a valid option.
static int Count_Fix()
{
var num = 0;
while (true)
{
Console.WriteLine("Fix: How Many? (1/2)");
switch (Console.ReadLine())
{
case "Stop": // Breakout condition, we are leaving
return num;
case "1":
num += 1;
break;
case "2":
num += 2;
break;
default: // I didn't understand the input. Let me ask again.
break;
}
};
return num;
}
Finally if you wan't to have some conditional loop back or exit you can do it with a if/else:
static int Count_Fix()
{
var num = 0;
while (true)
{
Console.WriteLine("Fix: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
break;
case "2":
num += 2;
if (num % 2 == 0) break; // conditional go back or exit
else return num; // exit
default: // I didn't understand the input. Let me ask again.
break;
}
};
}
i'm very new to C# (well, programming in general)
I am trying to create a menu for a c# console application. The the menu keeps reappearing after a selection from the menu is made... I've researched and tried many different options but nothing seems to be working for me.... I know it's something stupid that I've done incorrectly.
Any advice or guidance would be very much appreciated. Thanks in advanced.
static void Main() //Start of program
{
//Menu and other UI stuff
int userSelection = 0;
do
{
Console.WriteLine("[1] Encryption");
Console.WriteLine("[2] Decryption");
Console.WriteLine("[3] Exit");
Console.Write ("Please choose an option 1-3: ");
userSelection = Int32.Parse(Console.ReadLine());
switch(userSelection)
{
case 1:
readFile();
break;
case 2:
decryption();
break;
case 3:
Environment.Exit(0);
break;
default:
Console.WriteLine("Your selection is invalid. Please try again.");
break;
}
}
while (userSelection != 4);
}
Your do/while only will stops when your userSelection have value 4, in this example, it never will happen.
change your while condition to
while(userSelection <= 0 || userSelection > 3)
it should solve...
maybe you would like to use something like:
int userSelection = 0;
bool validAnswer = false;
do
{
Console.WriteLine("[1] Encryption");
Console.WriteLine("[2] Decryption");
Console.WriteLine("[3] Exit");
Console.Write ("Please choose an option 1-3: ");
userSelection = Int32.Parse(Console.ReadLine());
switch(userSelection)
{
case 1:
readFile();
validAnswer = true;
break;
case 2:
decryption();
validAnswer = true;
break;
case 3:
validAnswer = true;
Environment.Exit(0);
break;
default:
Console.Clear();
Console.WriteLine("Your selection is invalid. Please try again.");
break;
}
}while (!validAnswer);
It keeps reappearing because you placed your code in a do while loop. If you want to run this code only once don't use looping constructs, just place it directly in Main.
If you use something like
do
{
// ...
}
while (userSelection != 4);
the code inside the loop will be repeated until the user enters 4.
From msdn article on a do while:
The do statement executes a statement or a block of statements
repeatedly until a specified expression evaluates to false.
Another option would be to use a break statement after the switch block.
class Program
{
static void Main() //Start of program
{
//Menu and other UI stuff
string userSelection;
do
{
Console.Clear();
Console.WriteLine("[1] Encryption");
Console.WriteLine("[2] Decryption");
Console.WriteLine("[3] Exit");
Console.Write("Please choose an option 1-3: ");
userSelection = Console.ReadLine();
switch (userSelection)
{
case "1":
Console.WriteLine("mission 1");
break;
case "2":
Console.WriteLine("mission 2");
break;
case "3":
Environment.Exit(0);
break;
default:
Console.WriteLine("Your selection is invalid. Please try again.");
break;
}
Console.ReadLine();
}
while (true);
}
}
I have looked really hard on this. Integers seem easy, but this is what I have been trying to figure out in C# in visual studio.
I want to have a user input of a letter like "a" then the console writes "apple", b=bobby, c=charlie, etc. and when they don't put a letter then it gives an error message like "no letters used". I am not sure if I am suppose to convert the user input from a string with ToChar or what the best way to do this is. I haven't gotten into arrays yet and haven't figured out the switch command with characters (instead of integers or strings).
This is how I was trying to do it:
Console.WriteLine("Enter a letter ");
choice = Convert.ToChar(Console.ReadLine());
if (char choice = 'a'){
Console.WriteLine("apple");
}else if (char choice = 'b'{
Console.WriteLine("bobby");
}else if (char choice = 'b'{
Console.WriteLine("bobby");
}else (char choise=!IsLetter){
Console.WriteLine("No Letters entered");
If you want to stick to if else, here is what you can do:
if (choice == 'a')
{
Console.WriteLine("apple");
}
else if (choice =='b')
{
Console.WriteLine("bobby");
}
else if (char choice = 'c')
{
Console.WriteLine("charlie");
}
else
{
Console.WriteLine("No Letters entered");
}
You don't need to put condition on your else anymore :)
Use a switch statement, probably best for your scenario
static void Main(string[] args)
{
//initialise bool for loop
bool flag = false;
//While loop to loop Menu
while (!flag)
{
Console.WriteLine("Menu Selection");
Console.WriteLine("Press 'a' for apple");
Console.WriteLine("Press 'b' for bobby");
Console.WriteLine("Type 'exit' to exit");
//Read userinput
//Store inside string variable
string menuOption = Console.ReadLine();
switch (menuOption)
{
case "a":
//Clears console for improved readability
Console.Clear();
//"\n" Creates empty line after statement
Console.WriteLine("apple has been selected\n");
//Break out of switch
break;
case "b":
Console.Clear();
Console.WriteLine("bobby has been selected\n");
break;
case "exit":
Console.Clear();
Console.WriteLine("You will now exit the console");
//bool set to false to exit out of loop
flag = true;
break;
//Catch incorrect characters with default
default:
Console.Clear();
//Error message
Console.WriteLine("You have not selected an option\nPlease try again\n\n");
break;
}
}
Console.ReadLine();
This is how you write it using a switch:
switch (choice){
case 'a':
Console.WriteLine("apple");
break;
case 'b':
Console.WriteLine("bobby");
break;
case 'c':
Console.WriteLine("charlie");
break;
default:
Console.WriteLine("No Letters entered");
break;
}
I have a method that appends or inserts characters to the text of either a combo box or textbox depending on what was last focused on. I am using buttons to pass in the character as a parameter, Using a keyboard or sendkeys is not an option. When my method appends or inserts characters into a textbox the result is as expected however when the same method is applied to a combobox the text of the combobox is highlighted. Obviously this is not the functionality im looking for and I believe this is stopping the autocomplete mode from working correctly.
Why is the combobox behaving differently than the textbox?
The code:
private void createText(string lowerCaseChar, string upperCaseChar)
{
Control FocusedTextComboBox;
switch (lastTextComboBoxFocused)
{
case 54:
FocusedTextComboBox = SearchTextBox;
break;
case 4:
FocusedTextComboBox = VendorComboBox;
break;
case 6:
FocusedTextComboBox = SectionComboBox;
break;
case 5:
FocusedTextComboBox = DeptComboBox;
break;
default:
FocusedTextComboBox = SearchTextBox;
break;
}
if (FocusedTextComboBox is TextBox)
{
TextBox FocusedTextBox = (TextBox)FocusedTextComboBox;
int SelectionStartNumber = FocusedTextBox.SelectionStart;
switch (shift)
{
case true:
FocusedTextBox.Text = FocusedTextBox.Text.Insert(FocusedTextBox.SelectionStart, upperCaseChar);
break;
case false:
FocusedTextComboBox.Text = FocusedTextComboBox.Text.Insert(FocusedTextBox.SelectionStart, lowerCaseChar);
break;
}
FocusedTextBox.SelectionStart = SelectionStartNumber + 1;
FocusedTextBox.Focus();
}
else
{
ComboBox FocusedComboBox = (ComboBox)FocusedTextComboBox;
if (FocusedComboBox.SelectionStart == 0 && FocusedComboBox.Text != "")
{
switch (shift)
{
case true:
FocusedComboBox.Text += upperCaseChar;
break;
case false:
FocusedComboBox.Text += lowerCaseChar;
break;
}
}
else
{
int SelectionStartNumber = FocusedComboBox.SelectionStart;
switch (shift)
{
case true:
FocusedComboBox.Text = FocusedComboBox.Text.Insert(FocusedComboBox.SelectionStart, upperCaseChar);
break;
case false:
FocusedTextComboBox.Text = FocusedTextComboBox.Text.Insert(FocusedComboBox.SelectionStart, lowerCaseChar);
break;
}
FocusedComboBox.SelectionStart = SelectionStartNumber + 1;
}
FocusedComboBox.Focus();
}
}
I think setting focus back to the combobox is highlighting the text, move FousedCombox.Focus() to before assigning text to combobox.
could I turn this into a switch statement ?
if (donation_euro.Text.Trim().Equals(""))
{
donation_euro.Text = "00.00";
}
if (donation_lui.Text.Trim().Equals(""))
{
donation_lui.Text = "00.00";
}
if (donation.Text.Trim().Equals(""))
{
donation.Text = "00.00";
}
No, because your are not switching on a single variable, but multiple.
I suspect your motivation to do this, is to make the code more readable ? If this is the case, you could put the common logic of your three if's into a method, to reuse the code and better convey the intent.
Not Possible.as switch takes Expression and executes the matching Constant Case Label.
From MSDN :Switch-Case
Each case label specifies a constant value. The switch statement
transfers control to
the switch section whose case label matches
the value of the switch expression
Switch(Expression)
{
case constant1://statements
break;
case constant2://statements
break;
case constant3://statements
break;
}
if you want to switch with single value then it is possible
int a = 3;
if (a == 1)
{
//statements
}
else if(a == 2)
{
//statements
}
else if(a == 3)
{
//statements
}
else if(a == 4)
{
//statements
}
else
{
//statements
}
can be converted into switch as below:
int a = 3;
switch(a)
{
case 1: //statements
break;
case 2: //statements
break;
case 3: //statements
break;
case 4: //statements
break;
default : //statements
break;
}