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
Related
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")
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.
I came across article which explains how to do password strength validation.
I am having a problem with the errors I am encountering. One error states: Cannot implicitly convert type 'System.Text.RegularExpressions.Match' to 'bool' which is on line if (Regex.Match(password, #"/\d+/",...
The other error says: Operator '&&' cannot be applied to operands of type 'System.Text.RegularExpressions.Match' and 'System.Text.RegularExpressions.Match' which happens on line where AND or && statement is.
I don't understand why Regex statement isn't converting to bool type? And second problem is probably connected to the first one.
How can I fix this?
enum PasswordScore
{
Blank = 0,
VeryWeak = 1,
Weak = 2,
Medium = 3,
Strong = 4,
VeryStrong = 5
}
private static PasswordScore CheckStrength(string password)
{
int score = 1;
if (password.Length < 1)
return PasswordScore.Blank;
if (password.Length < 4)
return PasswordScore.VeryWeak;
if (password.Length >= 8)
score++;
if (password.Length >= 12)
score++;
if (Regex.Match(password, #"/\d+/", RegexOptions.ECMAScript))
score++;
if (Regex.Match(password, #"/[a-z]/", RegexOptions.ECMAScript) &&
Regex.Match(password, #"/[A-Z]/", RegexOptions.ECMAScript))
score++;
if (Regex.Match(password, #"/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/",
RegexOptions.ECMAScript))
score++;
return (PasswordScore)score;
}
You need to use IsMatch, not Match. IsMatch returns a bool, while Match returns a Match object which gives you more detail (captured groups, etc)
Regex.Match() returns a Match object, not a boolean. You probably want to check the match.Success property, i.e.
var result = Regex.Match(...);
if(result.Success)
score++;
If success is all you care about, then just use the Success property of Match:
if (Regex.Match(password, #"/\d+/", RegexOptions.ECMAScript).Success)
and:
if (Regex.Match(password, #"/[a-z]/", RegexOptions.ECMAScript).Success &&
Regex.Match(password, #"/[A-Z]/", RegexOptions.ECMAScript).Success)
Regex.Match returns a Match type. See this link for official documentation
You will want to change your code to:
if(Regex.Match(...).Success) {
...
}
Or something very similar.
I am currently converting vb and vb.net to c# but have an issue. I would strongly like not to use the visualbasic dlls in the converted code and have been doing this fine so far.
But this code
Dim x as Double 'this was error saying it was integer
x = Val("1 23 45 x 6") ''#x is 12345
x = Val("1..23") ''#x is 1.23
x = Val("1 1,,,,,2,2..3") ''#x is 1122.3
Does not work the same as vb6 even with using "Val" from the visualbasic.conversion.dll Is there anyone that has solved this to work the same? A c# solution would be best.
None of the above seemed to satisfy my needs, so I wrote the following:
public static Double Val(string value)
{
String result = String.Empty;
foreach (char c in value)
{
if (Char.IsNumber(c) || (c.Equals('.') && result.Count(x => x.Equals('.')) == 0))
result += c;
else if (!c.Equals(' '))
return String.IsNullOrEmpty(result) ? 0 : Convert.ToDouble(result);
}
return String.IsNullOrEmpty(result) ? 0 : Convert.ToDouble(result);
}
Results of the test data:
"0 1 5.2123 123.123. 1 a" returns 15.21233123
" 1 5.2123 123a" returns 15.21233123
"a1 5.2123 123.123. 1 a" returns 0
"" returns 0
I know nothing of this VisualBasic.Conversion.dll (and neither does google), but the Microsoft.VisualBasic namespace (in Microsoft.VisualBasic.dll) is part of the core framework and perfectly fine and acceptable to use from C#. There are other nice gems in there as well (ie TextFieldParser), but this should have the exact Val() implementation you need.
If this is the library you've already tried and it doesn't seem right, then I'd go take another look at the unit tests on it.
Outside of this, the accepted ways in C# for converting strings to integers are int.Parse(), int.TryParse(), and Convert.ToInt32(). But, like it or not, the Val() function from the Microsoft.VisualBasic.dll library is the closest match you're going to find for your code's existing behavior.
Check out this site: http://www.dreamincode.net/forums/topic/36064-val-replacement/ where others give an example how to implement your own Val() function.
You could use the Convert static class. It's pretty close to Val() but you need to specify the convert to type. It's in the System namespace.
E.g.:
int x = Convert.ToInt32("23");
int y = Convert.ToDouble("23.342");
http://msdn.microsoft.com/en-us/library/system.convert(v=vs.71).aspx
There is no exact equivalent of vb6 val function in C#. But this function can be used by using Microsoft.VisualBasic namespace in C#.
To use val() function in C# add Microsoft.VisualBasic namespace and use following code:
Conversion.Val("09sdf");
From your examples it could look similar to this. But since I don't know the VB val specification it might not work on all strings correctly.
Decimal ParseNumerString(string s)
{
Decimal value=0;
Decimal multiplier=1;
bool decimalPart=false;
foreach(char c in s)
{
if(IsDigit(c))
{
int i=ParseDigit(c);
if(!decimalPart)
{
value=value*10+i;
}
else
{
muliplier/=10;
value=value+multiplier*i;
}
if(c=='.')
decimapPart=true;
}
return value;
}
This is pseudocode you need to implement parse digit and is digit yourself(trivial). I chose Decimal as internal representation because that way I don't get strange rounding errors in the fractional part.
Had the same issue, started with #ericosg 's answer, then realized I needed Negative Numbers and Scientific Notation
namespace VB6
{
public class Helper
{
public static double Val(object value)
{
double returnVal = 0;
string sToParse = value.ToString();
string result = string.Empty;
string num = string.Empty; //In the case of scientific notation e.g. 3e5 = 300000
foreach (char c in sToParse)
{
if (result.Length == 0 && c.Equals('-'))//negative numbers
result += c;
else if (Char.IsNumber(c) || (c.Equals('.') && result.Count(x => x.Equals('.')) == 0))
result += c;
else if ((c.Equals('e') || c.Equals('E')) && num.Length == 0 && result.Length != 0) //scientific notation
{
num = result;
result = string.Empty;
}
else if (!c.Equals(' '))
{
break;
}
}
if (num.Length > 0)
{
//scientific notation
double fSignificantFigures = string.IsNullOrEmpty(result) || result == "-" ? 1 : Math.Pow(10, Convert.ToDouble(result));
returnVal = num == "-" ? 0 : Convert.ToDouble(num) * fSignificantFigures;
}
else
{
returnVal = string.IsNullOrEmpty(result) || result == "-" ? 0 : Convert.ToDouble(result);
}
return returnVal;
}
}
}
I have enum list and method and i get error: " not all code paths return a value"
Some idea whats wrong in my method ? I am sure I always return STANY type :/
Thanks for help :)
private enum STANY { PATROL, CHAT, EAT, SEARCH, DIE };
private STANY giveState(int id, List<Ludek> gracze, List<int> plansza)
{
// Sprawdz czy gracz stoi na polu z jedzeniem i nie ma 2000 jednostek jedzenia
bool onTheFood = false;
onTheFood = CzyPoleZjedzeniem(id, gracze, plansza, onTheFood);
if (onTheFood && (gracze[id].IloscJedzenia < startFood / 2))
return STANY.EAT;
// Sprawdz czy gracz nie stoi na polu z innym graczem
bool allKnowledge = true;
allKnowledge = CzyPoleZInnymGraczem(id, gracze, allKnowledge);
if (!allKnowledge)
return STANY.CHAT;
// Jesli ma ponad i rowna ilosc jedzenia patroluj
if (gracze[id].IloscJedzenia >= startFood / 2)
return STANY.PATROL;
// Jesli ma mniej niz polowe jedzenia szukaj jedzenia
if (gracze[id].IloscJedzenia > 0 && gracze[id].IloscJedzenia < startFood / 2)
return STANY.SEARCH;
// Jesli nie ma jedzenia umieraj
if (gracze[id].IloscJedzenia <= 0)
return STANY.DIE;
}
there's no return if none of those if conditions are met. You need to either use if...elseif...else
or have a return after all of the if statements that will return a value if nothing has been returned (none of the if conditions were met).
Maybe you're sure that a return type will always be given, but the compiler isn't [imagine that all the if conditions fail - ie: a variable was changed while your code was executing by an external program. Then what would happen?]
Just stick a return at the bottom as a "default" value. You could also throw an exception too, if you want, since the bottom should never be reached, right?
This has nothing to do with the fact that you're returning an ENUM, and everything to do with the fact that the compiler detects that there are cases where you never call RETURN with any value.
You should add a return statement at the bottom of your function that returns some default value.
This is because every return statement is preceded by an if statement. Therefore, if all of your if statements are false, no value will be returned. If it's impossible for all if statements to be false, remove if (gracze[id].IloscJedzenia <= 0), as it's redundant. If not, add a return null; or something at the end, or throw an error.
Replace this:
// Jesli nie ma jedzenia umieraj
if (gracze[id].IloscJedzenia <= 0)
return STANY.DIE;
With this:
// Jesli nie ma jedzenia umieraj
// (gracze[id].IloscJedzenia <= 0)
return STANY.DIE;
Leave the redundant line in the comment as documentation.
The compiler's static analysis (i.e. the code that is designed to check for this condition) is not always 100% accurate. But when it's not 100% accurate, the compiler will tend to err on the side of giving a false positive (that is, saying it doesn't return from all paths) than a false negative (that is, not saying it doesn't return from all paths).
So add a return at the bottom, use a series of "if .. else if ... else" statements instead, or throw an exception to indicate that the condition is "impossible".