Random number and switch statement - c#

if (((turn % 2) != 0) && (vsComputer))
{
int generateAI = generateRandomAI(AI);
switch (generateAI)
{
case 0:
computerMedio();
break;
case 1:
computerDifficile();
break;
}
}
I want my 0/1 value to be the same for all the game.
With the code I wrote, on every move it selects a different AI mode.
It shouldn't be that hard to achieve, but I can't find a solution.
Thanks everyone!

Your issue is:
int generateAI = generateRandomAI(AI);
You are generating a new random value on every invocation of this code block. If you wish to keep the same value for all execution, just generate the value once and keep it in scope.

Ok I solved in the following way
public Boolean difficult;
in the newGame() method I generate the number which lasts for all the game.
then,
switch (generateAI)
{
case 0:
difficult = false;
break;
case 1:
difficult = true;
break;
}
into the game:
if (((turn % 2) != 0) && (vsComputer))
{
if (difficult)
{
computerDifficile();
}
else
{
computerMedio();
}
}

Related

Detect if result is 0 , -4 or something else?

I have a method which has result at the end,I would want to detect if number is not 0 and if it's -4.
0 Means good
-4 Means something that can be solve
And anything else is bad.
Like
if ( Result != 0)
{
MessageBox.Show("It's bad!")
}
else if ( Result == -4)
{
Thread.Sleep(20000);
MyMethod.TryAgain();
}
else
{
MessageBox.Show("It's good");
}
My problem is that -4 is not 0,so if i get result -4 it takes my Result != 0 method. How can I solve it? Thank you in advance.
Use switch and case.
switch (Result) {
case 0:
MessageBox.Show("It's good");
break;
case -4:
Thread.Sleep(20000);
MyMethod.TryAgain();
break;
default:
MessageBox.Show("It's bad!");
break;
}
Microsoft documentation: https://msdn.microsoft.com/en-us/library/06tc147t(v=vs.110).aspx
Just reorder your if-structure to the following:
if ( Result == 0)
{
MessageBox.Show("It's good")
}
else if ( Result == -4)
{
Thread.Sleep(20000);
MyMethod.TryAgain();
}
else
{
MessageBox.Show("It's bad");
}
So your initial problem, that the Result != 0 case is evaluated first, is gone.
Simply change order of branches
if (Result == -4) \\ solve
else if (Result != 0) \\ bad
else \\ good
When you are building a chain of non-exclusive conditions, start with the strongest one (i.e. the most specific condition). Otherwise the code for the weaker condition will execute, blocking access to more specific ones.
In your case, Result == -4 implies that Result != 0, meaning that the first condition is more specific than the second one. Hence you should check Result == -4 before Result != 0. Otherwise, Result == -4 would never be reached.
C# offers multiple ways of implementing this logic. As long as you follow a general rule of ordering your conditionals from most specific to least specific, picking a particular implementation is up to you.
Sorry, wrong code. See comment below.
switch(Result) {
case 0:
MessageBox.Show("It's bad!");
break;
case -4:
Thread.Sleep(20000);
MyMethod.TryAgain();
break;
default:
MessageBox.Show("It's good");
break;
}

Switch statement with multiple conditions on C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Could you tell me how to use switch with the below mentioned code snippet ?
if (IsSelectedOrganizer)
{
//
}
else if (IsNewOrganizer && IsOrganizerUserAlreadyExist)
{
//
}
else if (IsNewOrganizer && !IsOrganizerUserAlreadyExist)
{
//
}
else
{
//
}
But on Javascript we can do that as shown below.But C# it doesn't allow ? It says A constant value is expected
switch (true) {
case IsSelectedOrganizer:
//
break;
case IsNewOrganizer && IsOrganizerUserAlreadyExist:
//
break;
case IsNewOrganizer && !IsOrganizerUserAlreadyExist:
//
break;
}
That's a perfect use case for an if not for a switch, so i suggest to keep it. But you could improve it a little bit:
if (IsSelectedOrganizer)
{
//
}
else if (IsNewOrganizer)
{
if (IsOrganizerUserAlreadyExist)
{
//
}
else
{
//
}
}
else
{
//
}
A switch statement cannot have multiple conditions in it like if/else does, this is because switch is typically implemented as a fast in-program hashtable which means that: 1) All comparison values must be const, and 2) it doesn't actually perform as many comparisons as there are switch case expressions.
There is a "workaround" that requires converting a boolean expression into a custom enum value and then switching on that, but I don't see how it would be of any help in this situation.
That's not a great candidate for a switch statement as your logic depends on the values of several variable rather than checking a single variable for different values.
Here's an example of the sort of code that's easy to convert to a switch statement:
if (value == 0)
{
// do stuff
}
else if (value == 1)
{
// etc
}
As a switch statement that would be:
switch (value)
{
case 0:
// do stuff
break;
case 1:
// etc
break;
}
There's nothing wrong with using if...else if statements if you're checking combinations of different variables, as you are. If for some reason you have to use a switch statement, the best solution would be to create an enum with values representing each of your possible states, then switch on that. For example:
enum OrganizerType
{
SelectedOrganizer,
NewOrganizerUserExists,
NewOrganizerUserDoesntExist
}
// ...
OrganizerType orgType = calculateOrgType();
switch (orgType)
{
case SelectedOrganizer:
// do stuff
break;
// etc
}
As an exercise purely is "can it be done?", here's a solution. No developer, ever, should consider using this in real life though:
var switchValue = IsSelectedOrganizer ? 4 : 0 +
IsNewOrganizer ? 2 : 0 +
IsOrganizerUserAlreadyExist ? 1 : 0;
switch (switchValue)
{
case 7:
case 6:
case 5:
case 4:
// IsSelectedOrganizer part
break;
case 3:
// IsNewOrganizer && IsOrganizerUserAlreadyExist part
break;
case 2:
// IsNewOrganizer && !IsOrganizerUserAlreadyExist part
break;
default:
// else part
}
public int FlagValues
{
return (IsSelectedOrganizer & 1) + (IsNewOrganizer & 2) + (IsOrganizerUserAlreadyExists & 4)
}
switch (FlagValues)
In no respect better than using ifs but implemented using switchs ;-).
switch (IsSelectedOrganizer)
{
case true:
{
//
}
break;
default:
{
switch (IsNewOrganizer)
{
case true:
{
switch ((IsOrganizerUserAlreadyExist))
{
case true:
{
//
}
break;
default:
{
//
}
break;
}
}
break;
default:
{
//
}
break;
}
}
break;
}

ArgumentOutOfRange Exception thrown

I have been writing a Winforms application, in which the user selects something from a comboBox. However, when I run the application, the compiler throws an ArgumentOutOfRange Exception because the index was -1.
Code:
if (comboBox1.Enabled == false || comboBox2.Enabled == true || comboBox3.Enabled == false)
{
int index = comboBox2.SelectedIndex;
string t = comboBox2.Items[index].ToString();//<==EXCEPTION
switch (t)
{
case "Ounzes==>Pounds":
break;
case "Pounds==>Ounzes":
break;
case "Tons==>Pounds":
break;
case "Pounds==>Tons":
break;
case "Ounzes==>Tons":
break;
case "Tons==>Ounzes":
break;
case "Stone==>Pound":
break;
case "Pound==>Stone":
break;
case "Tons==>Stone":
break;
case "Stone==>Ton":
break;
}
}
Can anyone please explain why this exception is being thrown, because I did select something from the comboBox.
It appears that no item was selected in your ComboBox. Take a look at the documentation:
A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected.
The most obvious way to fix this is just to check to make sure an item has been selected before you try to use it, like this:
int index = comboBox2.SelectedIndex;
if (index >= 0)
{
string t = comboBox2.Items[index].ToString();
switch (t)
{
...
}
}
Check when your code is firing. Might be when combo1 is being populated, but combo2 hasn't yet.
As others have said quick way is to test selectedIndex >= 0 or selectItem != null.
The best thing to do would be,put the code in a try catch block and you'll find out answers for yourself :)

Is there an elegant way to replace if by something like switch when dealing with intervals?

Is there a way in .NET to replace a code where intervals are compared like
if (compare < 10)
{
// Do one thing
}
else if (10 <= compare && compare < 20)
{
// Do another thing
}
else if (20 <= compare && compare < 30)
{
// Do yet another thing
}
else
{
// Do nothing
}
by something more elegant like a switch statement (I think in Javascript "case (<10)" works, but in c#)? Does anyone else find this code is ugly as well?
One simplification: since these are all else-if instead of just if, you don't need to check the negation of the previous conditions. I.e., this is equivalent to your code:
if (compare < 10)
{
// Do one thing
}
else if (compare < 20)
{
// Do another thing
}
else if (compare < 30)
{
// Do yet another thing
}
else
{
// Do nothing
}
Since you've already affirmed that compare >= 10 after the first if, you really don't need the lower bound test on the second (or any of the other) ifs...
It's not pretty, but switch was originally implemented by hashing in C, so that it was actually faster than an if...else if chain. Such an implementation doesn't translate well to general ranges, and that's also why only constant cases were allowed.
However, for the example you give you could actually do something like:
switch(compare/10) {
case 0:
// Do one thing
break;
case 1:
// Do another thing
break;
case 2:
// Do yet another thing
break;
default;
// Do nothing
break;
}

Multiple cases in switch statement

Is there a way to fall through multiple case statements without stating case value: repeatedly?
I know this works:
switch (value)
{
case 1:
case 2:
case 3:
// Do some stuff
break;
case 4:
case 5:
case 6:
// Do some different stuff
break;
default:
// Default stuff
break;
}
but I'd like to do something like this:
switch (value)
{
case 1,2,3:
// Do something
break;
case 4,5,6:
// Do something
break;
default:
// Do the Default
break;
}
Is this syntax I'm thinking of from a different language, or am I missing something?
I guess this has been already answered. However, I think that you can still mix both options in a syntactically better way by doing:
switch (value)
{
case 1: case 2: case 3:
// Do Something
break;
case 4: case 5: case 6:
// Do Something
break;
default:
// Do Something
break;
}
There is no syntax in C++ nor C# for the second method you mentioned.
There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.
Original Answer for C# 7
In C# 7 (available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch statement and would help with the OP's problem.
Example:
int i = 5;
switch (i)
{
case int n when (n >= 7):
Console.WriteLine($"I am 7 or above: {n}");
break;
case int n when (n >= 4 && n <= 6 ):
Console.WriteLine($"I am between 4 and 6: {n}");
break;
case int n when (n <= 3):
Console.WriteLine($"I am 3 or less: {n}");
break;
}
// Output: I am between 4 and 6: 5
Notes:
The parentheses ( and ) are not required in the when condition, but are used in this example to highlight the comparison(s).
var may also be used in lieu of int. For example: case var n when n >= 7:.
Updated examples for C# 9
switch(myValue)
{
case <= 0:
Console.WriteLine("Less than or equal to 0");
break;
case > 0 and <= 10:
Console.WriteLine("More than 0 but less than or equal to 10");
break;
default:
Console.WriteLine("More than 10");
break;
}
or
var message = myValue switch
{
<= 0 => "Less than or equal to 0",
> 0 and <= 10 => "More than 0 but less than or equal to 10",
_ => "More than 10"
};
Console.WriteLine(message);
This syntax is from the Visual Basic Select...Case Statement:
Dim number As Integer = 8
Select Case number
Case 1 To 5
Debug.WriteLine("Between 1 and 5, inclusive")
' The following is the only Case clause that evaluates to True.
Case 6, 7, 8
Debug.WriteLine("Between 6 and 8, inclusive")
Case Is < 1
Debug.WriteLine("Equal to 9 or 10")
Case Else
Debug.WriteLine("Not between 1 and 10, inclusive")
End Select
You cannot use this syntax in C#. Instead, you must use the syntax from your first example.
With C#9 came the Relational Pattern Matching. This allows us to do:
switch (value)
{
case 1 or 2 or 3:
// Do stuff
break;
case 4 or 5 or 6:
// Do stuff
break;
default:
// Do stuff
break;
}
In deep tutorial of Relational Patter in C#9
Pattern-matching changes for C# 9.0
Relational patterns permit the programmer to express that an input
value must satisfy a relational constraint when compared to a constant
value
You can leave out the newline which gives you:
case 1: case 2: case 3:
break;
but I consider that bad style.
.NET Framework 3.5 has got ranges:
Enumerable.Range from MSDN
you can use it with "contains" and the IF statement, since like someone said the SWITCH statement uses the "==" operator.
Here an example:
int c = 2;
if(Enumerable.Range(0,10).Contains(c))
DoThing();
else if(Enumerable.Range(11,20).Contains(c))
DoAnotherThing();
But I think we can have more fun: since you won't need the return values and this action doesn't take parameters, you can easily use actions!
public static void MySwitchWithEnumerable(int switchcase, int startNumber, int endNumber, Action action)
{
if(Enumerable.Range(startNumber, endNumber).Contains(switchcase))
action();
}
The old example with this new method:
MySwitchWithEnumerable(c, 0, 10, DoThing);
MySwitchWithEnumerable(c, 10, 20, DoAnotherThing);
Since you are passing actions, not values, you should omit the parenthesis, it's very important. If you need function with arguments, just change the type of Action to Action<ParameterType>. If you need return values, use Func<ParameterType, ReturnType>.
In C# 3.0 there is no easy Partial Application to encapsulate the fact the the case parameter is the same, but you create a little helper method (a bit verbose, tho).
public static void MySwitchWithEnumerable(int startNumber, int endNumber, Action action){
MySwitchWithEnumerable(3, startNumber, endNumber, action);
}
Here an example of how new functional imported statement are IMHO more powerful and elegant than the old imperative one.
Here is the complete C# 7 solution...
switch (value)
{
case var s when new[] { 1,2,3 }.Contains(s):
// Do something
break;
case var s when new[] { 4,5,6 }.Contains(s):
// Do something
break;
default:
// Do the default
break;
}
It works with strings too...
switch (mystring)
{
case var s when new[] { "Alpha","Beta","Gamma" }.Contains(s):
// Do something
break;
...
}
The code below won't work:
case 1 | 3 | 5:
// Not working do something
The only way to do this is:
case 1: case 2: case 3:
// Do something
break;
The code you are looking for works in Visual Basic where you easily can put in ranges... in the none option of the switch statement or if else blocks convenient, I'd suggest to, at very extreme point, make .dll with Visual Basic and import back to your C# project.
Note: the switch equivalent in Visual Basic is Select Case.
Another option would be to use a routine. If cases 1-3 all execute the same logic then wrap that logic in a routine and call it for each case. I know this doesn't actually get rid of the case statements, but it does implement good style and keep maintenance to a minimum.....
[Edit] Added alternate implementation to match original question...[/Edit]
switch (x)
{
case 1:
DoSomething();
break;
case 2:
DoSomething();
break;
case 3:
DoSomething();
break;
...
}
private void DoSomething()
{
...
}
Alt
switch (x)
{
case 1:
case 2:
case 3:
DoSomething();
break;
...
}
private void DoSomething()
{
...
}
In C# 7 we now have Pattern Matching so you can do something like:
switch (age)
{
case 50:
ageBlock = "the big five-oh";
break;
case var testAge when (new List<int>()
{ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }).Contains(testAge):
ageBlock = "octogenarian";
break;
case var testAge when ((testAge >= 90) & (testAge <= 99)):
ageBlock = "nonagenarian";
break;
case var testAge when (testAge >= 100):
ageBlock = "centenarian";
break;
default:
ageBlock = "just old";
break;
}
One lesser known facet of switch in C# is that it relies on the operator= and since it can be overriden you could have something like this:
string s = foo();
switch (s) {
case "abc": /*...*/ break;
case "def": /*...*/ break;
}
gcc implements an extension to the C language to support sequential ranges:
switch (value)
{
case 1...3:
//Do Something
break;
case 4...6:
//Do Something
break;
default:
//Do the Default
break;
}
Edit: Just noticed the C# tag on the question, so presumably a gcc answer doesn't help.
I think this one is better in C# 7 or above.
switch (value)
{
case var s when new[] { 1,2 }.Contains(s):
// Do something
break;
default:
// Do the default
break;
}
You can also check Range in C# switch case: Switch case: can I use a range instead of a one number
OR
int i = 3;
switch (i)
{
case int n when (n >= 7):
Console.WriteLine($"I am 7 or above: {n}");
break;
case int n when (n >= 4 && n <= 6):
Console.WriteLine($"I am between 4 and 6: {n}");
break;
case int n when (n <= 3):
Console.WriteLine($"I am 3 or less: {n}");
break;
}
Switch case multiple conditions in C#
Or if you want to understand basics of
C# switch case
Actually I don't like the GOTO command too, but it's in official Microsoft materials, and here are all allowed syntaxes.
If the end point of the statement list of a switch section is reachable, a compile-time error occurs. This is known as the "no fall through" rule. The example
switch (i) {
case 0:
CaseZero();
break;
case 1:
CaseOne();
break;
default:
CaseOthers();
break;
}
is valid because no switch section has a reachable end point. Unlike C and C++, execution of a switch section is not permitted to "fall through" to the next switch section, and the example
switch (i) {
case 0:
CaseZero();
case 1:
CaseZeroOrOne();
default:
CaseAny();
}
results in a compile-time error. When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement must be used:
switch (i) {
case 0:
CaseZero();
goto case 1;
case 1:
CaseZeroOrOne();
goto default;
default:
CaseAny();
break;
}
Multiple labels are permitted in a switch-section. The example
switch (i) {
case 0:
CaseZero();
break;
case 1:
CaseOne();
break;
case 2:
default:
CaseTwo();
break;
}
I believe in this particular case, the GOTO can be used, and it's actually the only way to fallthrough.
Source
In C# 8.0 you can use the new switch expression syntax which is ideal for your case.
var someOutput = value switch
{
>= 1 and <= 3 => <Do some stuff>,
>= 4 and <= 6 => <Do some different stuff>,
_ => <Default stuff>
};
If you have a very big amount of strings (or any other type) case all doing the same thing, I recommend the use of a string list combined with the string.Contains property.
So if you have a big switch statement like so:
switch (stringValue)
{
case "cat":
case "dog":
case "string3":
...
case "+1000 more string": // Too many string to write a case for all!
// Do something;
case "a lonely case"
// Do something else;
.
.
.
}
You might want to replace it with an if statement like this:
// Define all the similar "case" string in a List
List<string> listString = new List<string>(){ "cat", "dog", "string3", "+1000 more string"};
// Use string.Contains to find what you are looking for
if (listString.Contains(stringValue))
{
// Do something;
}
else
{
// Then go back to a switch statement inside the else for the remaining cases if you really need to
}
This scale well for any number of string cases.
You can also have conditions that are completely different
bool isTrue = true;
switch (isTrue)
{
case bool ifTrue when (ex.Message.Contains("not found")):
case bool ifTrue when (thing.number = 123):
case bool ifTrue when (thing.othernumber != 456):
response.respCode = 5010;
break;
case bool ifTrue when (otherthing.text = "something else"):
response.respCode = 5020;
break;
default:
response.respCode = 5000;
break;
}
An awful lot of work seems to have been put into finding ways to get one of C# least used syntaxes to somehow look better or work better. Personally I find the switch statement is seldom worth using. I would strongly suggest analyzing what data you are testing and the end results you are wanting.
Let us say for example you want to quickly test values in a known range to see if they are prime numbers. You want to avoid having your code do the wasteful calculations and you can find a list of primes in the range you want online. You could use a massive switch statement to compare each value to known prime numbers.
Or you could just create an array map of primes and get immediate results:
bool[] Primes = new bool[] {
false, false, true, true, false, true, false,
true, false, false, false, true, false, true,
false,false,false,true,false,true,false};
private void button1_Click(object sender, EventArgs e) {
int Value = Convert.ToInt32(textBox1.Text);
if ((Value >= 0) && (Value < Primes.Length)) {
bool IsPrime = Primes[Value];
textBox2.Text = IsPrime.ToString();
}
}
Maybe you want to see if a character in a string is hexadecimal. You could use an ungly and somewhat large switch statement.
Or you could use either regular expressions to test the char or use the IndexOf function to search for the char in a string of known hexadecimal letters:
private void textBox2_TextChanged(object sender, EventArgs e) {
try {
textBox1.Text = ("0123456789ABCDEFGabcdefg".IndexOf(textBox2.Text[0]) >= 0).ToString();
} catch {
}
}
Let us say you want to do one of 3 different actions depending on a value that will be the range of 1 to 24. I would suggest using a set of IF statements. And if that became too complex (Or the numbers were larger such as 5 different actions depending on a value in the range of 1 to 90) then use an enum to define the actions and create an array map of the enums. The value would then be used to index into the array map and get the enum of the action you want. Then use either a small set of IF statements or a very simple switch statement to process the resulting enum value.
Also, the nice thing about an array map that converts a range of values into actions is that it can be easily changed by code. With hard wired code you can't easily change behaviour at runtime but with an array map it is easy.
A more beautiful way to handle that
if ([4, 5, 6, 7].indexOf(value) > -1)
//Do something
You can do that for multiple values with the same result
Just to add to the conversation, using .NET 4.6.2 I was also able to do the following.
I tested the code and it did work for me.
You can also do multiple "OR" statements, like below:
switch (value)
{
case string a when a.Contains("text1"):
// Do Something
break;
case string b when b.Contains("text3") || b.Contains("text4") || b.Contains("text5"):
// Do Something else
break;
default:
// Or do this by default
break;
}
You can also check if it matches a value in an array:
string[] statuses = { "text3", "text4", "text5"};
switch (value)
{
case string a when a.Contains("text1"):
// Do Something
break;
case string b when statuses.Contains(value):
// Do Something else
break;
default:
// Or do this by default
break;
}
We can also use this approach to achieve Multiple cases in switch statement... You can use as many conditions as you want using this approach..
int i = 209;
int a = 0;
switch (a = (i>=1 && i<=100) ? 1 : a){
case 1:
System.out.println ("The Number is Between 1 to 100 ==> " + i);
break;
default:
switch (a = (i>100 && i<=200) ? 2 : a) {
case 2:
System.out.println("This Number is Between 101 to 200 ==> " + i);
break;
default:
switch (a = (i>200 && i<=300) ? 3 : a) {
case 3:
System.out.println("This Number is Between 201 to 300 ==> " + i);
break;
default:
// You can make as many conditions as you want;
break;
}
}
}
Using new version of C# I have done in this way
public string GetValue(string name)
{
return name switch
{
var x when name is "test1" || name is "test2" => "finch",
"test2" => somevalue,
_ => name
};
}
For this, you would use a goto statement. Such as:
switch(value){
case 1:
goto case 3;
case 2:
goto case 3;
case 3:
DoCase123();
//This would work too, but I'm not sure if it's slower
case 4:
goto case 5;
case 5:
goto case 6;
case 6:
goto case 7;
case 7:
DoCase4567();
}

Categories