Selecting a specific item in listbox - c#

I have 6 items in my listbox.
I want to it so that if I click the first 2 in the listbox I can set a random number. I don't need to know how make a random number.
I thought it would be something like this:
if (listBox1.SelectedIndex = 1)
{
int no1 = random.Next(10, 50);
}
Just after 'if' I see the following error:
Cannot implicitly convert type 'int' to 'bool'

Should be: if (listBox1.SelectedIndex == 1)
The = operator is assignment, == is equality.

You need to use two equal signs to check for equality.
if (listBox1.SelectedIndex == 1)
{
int no1 = random.Next(10, 50);
}
You can read more about C# equality on MSDN.

Yes in case of int you can't use = operator to check equality you just need to check using == operator, ok in the case of bool compiler can't give any error but it can resign.mean to say.
if (listBox1.SelectedIndex == 1)
{
int no1 = random.Next(10, 50);
}
it's correct one in case of Bool
suppose you have to write.
bool test=false;
if(test=true)
{
//some code goes here
}
it won't give you compiler error it will reassign test.

Related

if statement does not work in c#

I have a fairly simple task which I want to do but something weird is happening. I just want to check if an element in a string equals zero and then set an integer accordingly.
This is my code
if (ssRow[(bar_position_row - 3)].Equals("0") && ssRow[(bar_position_row + 1)].Equals("0"))
{
back_row = 2;
front_row = 2;
}
else if (!ssRow[(bar_position_row - 3)].Equals("0") && !ssRow[(bar_position_row + 1)].Equals("0"))
{
back_row = 3;
front_row = 1;
}
else if (ssRow[(bar_position_row - 3)].Equals("0") && !ssRow[(bar_position_row + 1)].Equals("0"))
{
back_row = 2;
front_row = 1;
}
When I test my code, in several examples ssRow[(bar_position_row - 3)] and ssRow[(bar_position_row + 1)] equal zero but somehow the ssRow[(bar_position_row - 3)].Equals("0") and ssRow[(bar_position_row + 1)].Equals("0") are both FALSE. Does anyone know what my mistake is?
When you index into a string, what you get back is a char, not another string. You then compare this char to a string ("0"), and understandably get back false.
You should be comparing against '0' (a char), not "0" (a string). And since char is a value type, you can just use the == equality operator. If you had done so in the first place, this would have been a compile time error.
See example:
"abc"[0].Equals("a") //false
"abc"[0].Equals('a') //true
"abc"[0] == 'a' //true
"abc"[0] == "a" //compile-time error, can't compare char with string
I do not know the type of ssRow, if using index access on it does not return an string, then Equals("0") is doing object equality.
To fix it, consider using .ToString() first: ssRow[(bar_position_row - 3)].ToString().Equals("0")

going through a list with a for loop

Okay, i have a list and where i have structs stored, and i need to go through them from the last to the first, to check if one of the variables in the struct is 1. the code look like this:
for(int i = (checkpoints.Count - 1); i == 0; i--)
{
if(checkpoints[i].active == 1)
{
playerPositionX = checkpoints[i].xPosition;
playerPositionY = checkpoints[i].yPosition;
camPositionX = checkpoints[i].xPosition;
break;
}
}
this is the struct that i use:
private struct checkpoint
{
public int xPosition;
public int yPosition;
public int active;
}
what i need to do is to check if the variable active is == 1 in the struct that i have stored in the list. i have around 3-8 structs stored in the list. I need to start the check from the last struct in the list and work my way to the first.
when i try to debug the program it looks like it's not going from the last, but it starts at i=0.
please leave a comment if you have a fix, or if you need more information.
You can also use LastOrDefault() function. But, here can be one problem, because we are searching for Struct.
If nothing found?
LastOrDefault() will return default(checkpoint) if nothing found. The default value of a struct is the struct with all its values in turn default initialized. So, we must cast them to nullable using .Cast<checkpoint?>.
var activeCheckPoint = checkpoints
.Where(x => x.active == 1)
.Cast<checkpoint?>()
.LastOrDefault();
Or we must do the second check afterward that the returned object's active value is 1.
var activeCheckPoint = checkpoints.LastOrDefault(x => x.active == 1);
if(actactiveCheckPoint.active == 1)
{
// Then it is Ok
}
else
{
// Nothins was found
}
But, if you want to use for loop, then you must change i == 0 to i >= 0.
Your mistake was that you said to go though the loop if i was equal to 0, when it wasn't. You want the loop to loop until i is greater or equal to zero.
for(int i = (checkpoints.Count - 1); i >= 0; i--) // your mistake was here
{
if(checkpoints[i].active == 1)
{
playerPositionX = checkpoints[i].xPosition;
playerPositionY = checkpoints[i].yPosition;
camPositionX = checkpoints[i].xPosition;
break;
}
}

Best way to check multiple boolean conditions in C# if statements

I have 3 booleans on my code (C#) and an int32 property that depends on what booleans are true and false.
Whats the best way to accomplish this in another way than if statements like:
if(a && b && !c)
d = 1;
if(a && !b && !c)
d = 2;
//etc.. ect...
EDIT: The 3 booleans must have every combination possible to set the int32 value.
EDIT 2: The value of "d" can be the same for two different boolean comparations.
It is better to capture the intent of the operation instead of explicitly check the boolean values.
For example:
public void Check()
{
if (HasOrdered())
{
// do logic
}
}
private bool HasOrdered()
{
return a && !b && !c;
}
private bool HasBooked()
{
return a && b && !c;
}
You could use a Karnaugh map to reduce your equations and have fewer ifs.
https://en.wikipedia.org/wiki/Karnaugh_map
I think what your doing now is perfectly fine and any other solutions would be down to preference.
My preference, where it applies would be to separate the checks out if possible.
if (!a)
return;
if (!b)
return;
if (!c)
return;
This would be useful in the event that you need to check certain prereqs before issuing a function, like if the user has logged in, if a parameter exists and is in the right context, along with other items.
Like i said this might not apply but i just wanted to voice my opinion
You could do the lookup table hint given by #Adriano, assuming you have lookup_table filled with values for index [0..8):
var index = new [] { a,b,c }.Aggregate(0, (a,i) => return 2*a + (i?1:0));
int d = lookup_table[index];
Edit The EDIT of the question made this irrelevant: What does d mean?
If it's the count of false values (possible from the sample code), make it
int d = new [] { a,b,c }.Count(b => !b);
I don't see anything wrong with how you're doing it, but if the output is the same for multiple conditions you may be able to simplify if by creating a truth table and simplifying the conditions.
For example, if d should be 0 anytime a is false you could simplify to:
if(a)
if(b && !c)
d = 1;
if(!b && !c)
d = 2;
...
else
d = 0;
Or if there is some mathematical pattern (e.g. a, b, and c represent the three digits of a binary number) then you could do bit arithmetic.
If, however, you have 8 distinct outcomes (one for each combination of a, b, and c) then your method is fine.

Getting syntax error involving ';'

I am making a pokemon game and this section is giving me 3 errors:
"Invalid expression term ';' (CS1525)" and "; expected(CS1002)"
public class HeldItem
{
public static int CritCalc(bool item,bool skill, bool UsedItem,int dmg)
{
Random rand=new Random();
Action jump=new Action();
int i = rand()%100;
double CritPerc = 6.25;
if(item==true)
CritPerc=12.5;
else if(skill==true)
CritPerc=12.5;
else if(UsedItem==true)
CritPerc=12.5;
else if((item==true & skill== true) || (item==true & UsedItem == true) || (skill==true & UsedItem==true))
CritPerc=25%;
else if(item==true & skill == true & UsedItem==true)
CritPerc=33.3%;
if(Action) //jump
CritPerc = 50%;
if(i<CritPerc)
dmg=2*dmg;
else if(i>CritPerc)
dmg==dmg;
return dmg;
}
}
}
Maybe it is a silly problem but I don't know what it is
You cannot specify percents in C#.
You have the following lines:
CritPerc=25%;
CritPerc=33.3%;
CritPerc = 50%;
That is invalid (Percent indicates the modulo operator in C#).
Instead, you probably want to specify the values as double floating point values.
CritPerc=0.25;
CritPerc=0.333;
CritPerc = 0.50;
%(percent) operator in c# means modulo operation which takes two
operand. but you give one. So it gives error.
Instead of
CritPerc=25%;
write
CritPerc=.25;
or
CritPerc=25/100;
and
dmg==dmg
causes error.
The line that says:
dmg == dmg;
Ah, the fatal '=' error.
You have dmg ==dmg which is the wrong operator and if dmg already has the correct value just return it, dmg=dmg goes without saying

General Programming about IF else if statements C#

Well i got this if else statement where i have 12 variables that can either be 0, 1, or 2. if its a 0 its pass, if its 1 it fails, if its a 2 its unknown. I was wondering if anyone knows a shorter way of writing it in C#
here is what i have to write if there isn't
string pass = "pass";
string fail = "fail";
string unknown = "unknown"
if ( value == 0)
{
test1 = pass;
}
else if (value == 1)
{
test1 = fail;
}
else if (value == 2)
{
test1 = unknown;
}
if ( value1 == 0)
{
test2 = pass;
}
else if (value1 == 1)
{
test2 = fail;
}
else if (value1 == 2)
{
test2 = unknown;
}
.
.
.
if ( value12 == 0)
{
test13 = pass;
}
Let me explain a little more. I have 12 pictures on webpage, that need to be updated, depending on a database for the values. Each picture can be only 1 of 3 options and can change depending on the database. A pass(check mark), a fail(a red x) and an unknown (question mark). Let me know if you need more details.
Well i got this if else statement where i have 12 variables that can either be 0 1 or 2.
Any time you have several variables which you want to be able to treat in a similar way, you should use a collection for them, e.g. an array or a List<T>. If you don't already have a collection for them, you can create one:
int[] values = { value0, value, value2 /* etc * };
... although it would be better if you could have them as a collection from the very start.
Then you can iterate over all of them. It's not really clear why in this case you're overwriting the value of test in each block, but having a collection of inputs ends up with a natural way of creating a collection of outputs. You can also use a switch statement or a conditional expression to make the checks simpler. For example:
public static string ConvertValueToLabel(int value)
{
switch (value)
{
case 0: return "pass";
case 1: return "fail";
case 2: return "unknown";
// Adjust this behaviour as appropriate...
default: throw new ArgumentOutOfRangeException("value");
}
}
Or:
public static string ConvertValueToLabel(int value)
{
// Note that this doesn't do the same range checking as the version above
return value == 0 ? "pass"
: value == 1 ? "fail"
: "unknown";
}
(Some people don't like "stacking" conditionals like this, and I probably wouldn't use it in this case where a switch statement is probably more sensible, but it can be really handy.)
Looks like a case for arrays.
int[] values = { 1, 1, 2, 2, 1, 2 };
for (int i = 0; i < values.Length; i++)
{
if (values[i] == 1)
{
}
else if (values[i] == 2)
{
}
}//for
According to your code there is no need to check values 0-11 cause the test variable is changed again using value12. So you can just check the last value and and skip all other.
I would write a for loop which checks each variable. Or, at the very least, write the check as a function which can be referenced with each variable. Do the former if the variables are in series and their names can be determined sequentially. Do the later if the variable names are not really related to each other.
If necessary, place the variables into an array which can be looped through.

Categories