c# Switch issue. Homework - c#

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...

Related

c# . getting unreachable code error in switch statement

im getting unreachable code detected error in below code.
could anybudy pls guide on this issue , wil get bundle of thanks from bottom of my heart
public decimal SetDiscountLevel()
{
int range= spentAmount/500;
switch(range)
{
case 0:
return 0;
break;
case 1:
return 0.05m;
break;
case 2:
return 0.06m;
break;
case 3:
return 0.08m;
break;
default:
return 0.1m;
break;
}
}
Remove break; after return; keyword because if you use return; in case then break; will not be reached because you just stopped execution of loop with return; keyword.
See code below
public decimal SetDiscountLevel()
{
int range= spentAmount/500;
switch(range)
{
case 0:
return 0;
case 1:
return 0.05m;
case 2:
return 0.06m;
case 3:
return 0.08m;
default:
return 0.1m;
}
}
In each case you are immediately returning a value, meaning that the following break will never be executed.
Just do the following
public decimal SetDiscountLevel()
{
int range= spentAmount/500;
switch(range)
{
case 0:
return 0;
case 1:
return 0.05m;
case 2:
return 0.06m;
case 3:
return 0.08m;
default:
return 0.1m;
}
}

looping a switch statement in C# has strange error

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

Finding the index of chars that repeats

I'm really bad at explaining things, but I'll try my best.
I'm making a small program that converts one word into another as you type. Each letter that is typed goes through this section of code where it is changed to a different letter depending on its Index position of the whole word.
My issue here is that when there are repeating letters, the letters that repeat don't change according to their position within the word but rather the first occurrence.
For example this made up word "bacca". If you put that through the code, it SHOULD change to "vrwiy" but instead it changes to "vrwwr". I know why this is too. It's because the switch statement loops through the word that needs to be converted. However I'm without a clue on how to make it change each char according to it's own individual position within the index of the string. I thought maybe the LastIndexOf() method would work but instead it just reverses the order. So if I were to type the letter "a", it would come out as "n", but if I were to type "aa", it would switch the first "a" to "r" because the second is at the IndexOf 1 get's changed to "r".
private void inputTbox_TextChanged(object sender, EventArgs e)
{
List<string> rawZnWordList = new List<string>();
foreach (char a in inputTextBox.Text)
{
switch (inputTextBox.Text.IndexOf(a))
{
case 0:
switch (a)
{
case 'a':
rawZnWordList.Add("n");
continue;
case 'b':
rawZnWordList.Add("v");
continue;
case 'c':
rawZnWordList.Add("a");
continue;
default:
break;
}
continue;
case 1:
switch (a)
{
case 'a':
rawZnWordList.Add("r");
continue;
case 'b':
rawZnWordList.Add("x");
continue;
case 'c':
rawZnWordList.Add("z");
continue;
default:
break;
}
continue;
case 2:
switch (a)
{
case 'a':
rawZnWordList.Add("t");
continue;
case 'b':
rawZnWordList.Add("l");
continue;
case 'c':
rawZnWordList.Add("w");
continue;
default:
continue;
}
continue;
case 3:
switch (a)
{
case 'a':
rawZnWordList.Add("u");
continue;
case 'b':
rawZnWordList.Add("i");
continue;
case 'c':
rawZnWordList.Add("o");
continue;
default:
break;
}
continue;
case 4:
switch (a)
{
case 'a':
rawZnWordList.Add("y");
continue;
case 'b':
rawZnWordList.Add("m");
continue;
case 'c':
rawZnWordList.Add("d");
continue;
default:
break;
}
continue;
default:
break;
}
}
string finalZnWord = string.Join("", rawZnWordList.ToArray());
outputTextBox.Text = finalZnWord;
}
You should try using a for loop instead, like this:
for (int i = 0; i < inputTextBox.Text.Length; i++)
{
char a = inputTextBox.Text[i];
switch (i)
{
case 0:
switch (a)
...
Hope this helps ;).
You need to keep track of the index inside your foreach instead of using .IndexOf. You could also use a regular for loop instead of a foreach but this way is a minimal change to your code.
private void inputTbox_TextChanged(object sender, EventArgs e)
{
List rawZnWordList = new List();
int index = 0;
foreach (char a in inputTextBox.Text)
{
switch (index)
{
case 0:
switch (a)
{
case 'a':
rawZnWordList.Add("n");
continue;
case 'b':
rawZnWordList.Add("v");
continue;
case 'c':
rawZnWordList.Add("a");
continue;
default:
break;
}
continue;
case 1:
switch (a)
{
case 'a':
rawZnWordList.Add("r");
continue;
case 'b':
rawZnWordList.Add("x");
continue;
case 'c':
rawZnWordList.Add("z");
continue;
default:
break;
}
continue;
case 2:
switch (a)
{
case 'a':
rawZnWordList.Add("t");
continue;
case 'b':
rawZnWordList.Add("l");
continue;
case 'c':
rawZnWordList.Add("w");
continue;
default:
continue;
}
continue;
case 3:
switch (a)
{
case 'a':
rawZnWordList.Add("u");
continue;
case 'b':
rawZnWordList.Add("i");
continue;
case 'c':
rawZnWordList.Add("o");
continue;
default:
break;
}
continue;
case 4:
switch (a)
{
case 'a':
rawZnWordList.Add("y");
continue;
case 'b':
rawZnWordList.Add("m");
continue;
case 'c':
rawZnWordList.Add("d");
continue;
default:
break;
}
continue;
default:
break;
}
index++;
}
string finalZnWord = string.Join("", rawZnWordList.ToArray());
outputTextBox.Text = finalZnWord;
}
I think this does the same thing and is a lot more readable. Of course replace the letter rings with your own values. I only went up to 5 characters. I'm guessing you would want more.
//replacement letter rings
char[][] aRep = {
"xfhygaodsekzcpubitlvnjqmrw".ToCharArray(),
"wqtnsepkbalmzyxvordhjgifcu".ToCharArray(),
"nyxgmcibplovkwrszaehftqjud".ToCharArray(),
"soqjhpybuwfxvartkzginemdcl".ToCharArray(),
"pldquhegkaomcnjrfxiysvtbwz".ToCharArray(),
};
private string newText(string inVal)
{
char[] ia = inVal.ToCharArray(); //in array
int l = ia.Length;
char[] oa = new char[l]; //out array
for (int i = 0; i < l; i++)
oa[i] = aRep[i][(int)ia[i]-97]; //lowercase starts at char97
return new string(oa);
}
Here is also the code I used to generate the rings:
//generate random letter rings
//char[] ascii = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
//for (int i = 0; i < 8; i++)
// new string(ascii.OrderBy (x => Guid.NewGuid() ).ToArray()).Dump();
I did some very simple testing and this seemed quite a bit faster than the original approach and more importantly (to me) it is way more readable and a lot easier to see your replacement letter sequences. I think there is some more optimization to be done, but this i think is a good start. Just call this with your text during 'on change'.

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.

How add "or" in switch statements?

This is what I want to do:
switch(myvar)
{
case: 2 or 5:
...
break;
case: 7 or 12:
...
break;
...
}
I tried with "case: 2 || 5" ,but it didn't work.
The purpose is to not write same code for different values.
By stacking each switch case, you achieve the OR condition.
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
You do it by stacking case labels:
switch(myvar)
{
case 2:
case 5:
...
break;
case 7:
case 12:
...
break;
...
}
You may do this as of C# 9.0:
switch(myvar)
{
case 2 or 5:
// ...
break;
case 7 or 12:
// ...
break;
// ...
}
case 2:
case 5:
do something
break;
Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write
switch(myvar)
{
case 2:
case 5:
{
//your code
break;
}
// etc...
}
The example for switch statement shows that you can't stack non-empty cases, but should use gotos:
// statements_switch.cs
using System;
class SwitchTest
{
public static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = 0;
switch(n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or3.");
break;
}
if (cost != 0)
Console.WriteLine("Please insert {0} cents.", cost);
Console.WriteLine("Thank you for your business.");
}
}
Since C# 8 there are switch expressions that are better readable: no case, : and break;/return needed anymore. Combined with C# 9's logical patterns:
static string GetCalendarSeason(DateTime date) => date.Month switch
{
3 or 4 or 5 => "spring",
6 or 7 or 8 => "summer",
9 or 10 or 11 => "autumn",
12 or 1 or 2 => "winter",
_ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};
Limitation: with this syntax, at the right of the => you cannot use curly braces ({ and }) for statements.

Categories

Resources