looping a switch statement in C# has strange error - c#

I'm recently learning C# but I've run into a problem.
public static void PlayGame(Kion Player1,Kion Player2)
{
bool Win = false;
Console.WriteLine ("Let us begin then");
Console.WriteLine ("Press Enter to roll the dice ");
Console.ReadLine ();
Console.WriteLine ();
Console.WriteLine ();
Random Dice = new Random();
while (Win == false)
{
int DiceResult = Dice.Next (1,6);
switch(DiceResult) ***control cannot fall-through from one case label to another error message here***
{
case 1:
case 4:
Console.WriteLine ("The attribute being played is Strength");
if ((Player1.Pride == "Kan") & (Player2.Pride == "Kan"))
Console.WriteLine ("You are both proud Kans, you match in combat and do not lose health");
else
Console.WriteLine ("Those who belong to the 'Kan' pride unleashes their claws");
if (Player1.Pride == "Kan")
{
Player2.LoseHealth();
int PlayerNumber = 2;
LoseHealthText(PlayerNumber, Player2);
}
else
if (Player2.Pride == "Kan")
{
Player1.LoseHealth ();
int PlayerNumber = 1;
LoseHealthText(PlayerNumber, Player1);
}
else
Console.WriteLine ("None belong to the Kan, you will all hide this turn");
break;
case 3:
case 6:
Console.WriteLine ("hello");
}
}
}
The code above cannot execute because the compiler reports an error of control cannot fall-through from case label to another on the line where there is the switch(DiceResult) statement.
Can someone help my identify where my mistake is?

case 3:
case 6:
Console.WriteLine ("hello");
Here you need a break; statement, like this:
case 3:
case 6:
Console.WriteLine ("hello");
break;
In C#, you can't create a case option without break;, return; or throw statement. Please refer MSDN| for more information.

try putting a break after
Console.WriteLine ("The attribute being played is Strength");
so you have:
switch(DiceResult) // **control cannot fall through case on this line**
{
case 1:
case 4:
Console.WriteLine ("The attribute being played is Strength");
break;
}

Related

c# Switch case does not continue after try catch - Need a loop to enter a valid data type

When i introduce the "try" "catch" statements and read the user input for the "choice" variable, the code executes as it should it does not however continue on to the "switch" "case" statement as the "choice" variable is then said to be an unassigned local variable. Please help.
I was expecting the rest of the "switch case" code to execute.
int choice;
do
{
Console.Clear();
Console.WriteLine("1. Load Data");
Console.WriteLine("2. Add Customer");
Console.WriteLine("3. Sort Customers");
Console.WriteLine("4. Display Customers");
Console.WriteLine("5. Edit Customer");
Console.WriteLine("6. Exit\n");
Console.WriteLine("Chose an option 1-6: ");
bool valid = true;
do
{
try
{
choice = Convert.ToInt32(Console.ReadLine());
}
catch (Exception)
{
valid = false;
Console.WriteLine("please enter a number from 1 - 6");
}
} while (valid == false);
switch (choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
break;
}
Console.Clear();
} while (choice != 6);
When the catch block is executed, then choice is not assigned a value in the try block.
Assign a value to choice in the catch block
int choice; // Choice is declared here but is not assigned a value.
...
try
{
// When the conversion fails, no assignment to `choice` is made.
choice = Convert.ToInt32(Console.ReadLine());
valid = true; // This was also missing.
}
catch (Exception)
{
valid = false;
choice = 0; // <========================================
Console.WriteLine("please enter a number from 1 - 6");
}
...
// Now, here `choice` is known to have a value assigned in any case.
Note that the compiler does not consider the value of valid nor does the compiler analyze how it affects the control flow when is says that choice may be unassigned. The error message is based solely on a static analysis of the control flow for assignments made to choice itself.
But it would be easier to use TryParse instead of catching an exception.
int choice;
do {
// Console output ...
while (!Int32.TryParse(Console.ReadLine(), out choice)) {
Console.Write("please enter a number from 1 - 6: ");
}
Console.WriteLine();
switch (choice) {
...
default:
break;
}
Console.Clear();
} while (choice != 6);
Sir I think i have just solved it. I have added a Break; statement to the try block. in this case the code loops back to the beginning and allows the user to enter the correct data type again and the switch statement continues.
bool valid = true;
do
{
try
{
choice = Convert.ToInt32(Console.ReadLine());
break;
}
catch (Exception)
{
Console.Clear();
valid = false;
choice = 0;
Console.WriteLine("please enter a number from 1 - 6");
}
} while (valid == false);
You can just assign a value when you decleare choice
int choice = 0;
You have also to set the valid variable at true at the start of the loop.
bool valid;
do
{
valid = true;
try
{
choice = Convert.ToInt32(Console.ReadLine());
}
catch (Exception)
{
valid = false;
Console.WriteLine("please enter a number from 1 - 6");
}
} while (valid == false);

how to return to the start of a switch statement after case complete

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

Console application Menu issues in c#

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

Trying to make a Simple User input to character output Console program

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

c# Switch issue. Homework

This is what I have so far. My problem is that none of the cases are responding when you enter either the correct or incorrect answer. I'm not really sure where to go from here. The program asks you answer two random numbers being multiplied. And then it should give you one of the eight responses.
int result = 0;
int caseSwitch = 0;
string question = DoMultiplication(out result);
Console.WriteLine(question);
int answer = Convert.ToInt32(Console.ReadLine());
if (answer == result)
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("Very Good");
break;
case 2:
Console.WriteLine("Excellent");
break;
case 3:
Console.WriteLine("Nice Work");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
}
}
else
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("No, Please Try Again.");
break;
case 2:
Console.WriteLine("Wrong, Try Once More");
break;
case 3:
Console.WriteLine("Don't Give Up!");
break;
case 4:
Console.WriteLine("No, Keep Trying!");
break;
caseSwitch is always 0, so your switch will always fall through without writing anything to console.
If you want a random response you could do something like this:
int result = 0;
int caseSwitch = new Random().Next(1, 4);
string question = DoMultiplication(out result);
Console.WriteLine(question);
int answer = Convert.ToInt32(Console.ReadLine());
if (answer == result)
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("Very Good");
break;
case 2:
Console.WriteLine("Excellent");
break;
case 3:
Console.WriteLine("Nice Work");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
}
}
else
{
switch (caseSwitch)
{
case 1:
Console.WriteLine("No, Please Try Again.");
break;
case 2:
Console.WriteLine("Wrong, Try Once More");
break;
case 3:
Console.WriteLine("Don't Give Up!");
break;
case 4:
Console.WriteLine("No, Keep Trying!");
break;
CaseSwitch is always = 0.
You need to assign a value to it, and-or add a default case to your switch.
You have your int caseSwitch = 0; and I don't see you changing it in your code to any of 1-4. So what do you expect it to do if you dont have the caseSwitch changed...

Categories

Resources